Java Tutorial/File/Scanner — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:20, 1 июня 2010

Creating a Scanner: read from standard input: Scanner conin = new Scanner(System.in)

import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) {
    Scanner conin = new Scanner(System.in);
    int count = 0;
    System.out.println("Enter numbers to average.");
    while (conin.hasNext()) {
      if (conin.hasNextDouble()) {
        System.out.println(conin.nextDouble()); 
        count++;
      }
      if(count == 3){
        System.exit(0);
        
      }
    }
  }
}





Creating a Scanner to read from a string

import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) {
    String instr = "10 99.88 scanning is easy.";
    Scanner conin = new Scanner(instr);
    while (conin.hasNext()) {
      if (conin.hasNextDouble()) {
        System.out.println(conin.nextDouble()); 
      }
    }
  }
}



10.0
99.88


In general, to use Scanner, follow this procedure

  1. Call one of Scanner"s hasNextXXX methods to see if the input is available
  2. If available, call Scanner"s nextXXX to read the input.
  3. Repeat first two steps.



Scanner conin = new Scanner(System.in);
int i;
// Read a list of integers. 
while(conin.hasNextInt()) {
  i = conin.nextInt();
  // ...
}





Searching for the specified pattern within the next line of text

  1. String findInLine(Pattern pattern)
  2. String findInLine(String pattern)

If the pattern is found, the matching token is consumed and returned. Otherwise, null is returned.



import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) {
    Scanner sc = new Scanner("Name: Tom Age: 28 ID: 77");
    sc.findInLine("ID:");
    if (sc.hasNext())
      System.out.println(sc.next());
    else
      System.out.println("Error!");
  }
}



77


Setting Delimiters for Scanner

Scanner defines where a token starts and ends based on a set of delimiters.

The default delimiters are the whitespace characters.

To Change the delimiters

  1. Scanner: useDelimiter(String pattern)
  2. Scanner: useDelimiter(Pattern pattern)
  3. Pattern is a regular expression that specifies the delimiter set.

Use Scanner to compute the average of a list of comma-separated values.



import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) throws IOException {
    FileWriter fout = new FileWriter("test.txt");
    fout.write("2, 3.4,    5,6, 7.4, 9.1, 10.5, done");
    fout.close();
    FileReader fin = new FileReader("Test.txt");
    Scanner src = new Scanner(fin);
    // Set delimiters to space and comma.
    // ", *" tells Scanner to match a comma and zero or more spaces as
    // delimiters.
    src.useDelimiter(", *");
    // Read and sum numbers.
    while (src.hasNext()) {
      if (src.hasNextDouble()) {
        System.out.println(src.nextDouble());
      } else {
        break;
      }
    }
    fin.close();
  }
}



2.0
3.4
5.0
6.0
7.4
9.1
10.5


To find within the next count characters

  1. String findWithinHorizon(Pattern pattern, int count)
  2. String findWithinHorizon (String pattern, int count)

If successful, it returns the matching pattern. Otherwise, it returns null.

If count is zero, then all input is searched until either a match is found or the end of input is encountered.



import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) {
    Scanner sc = new Scanner("Name: Tom Age: 28 ID: 77");
    sc.findWithinHorizon("ID:",100);
    if (sc.hasNext())
      System.out.println(sc.next());
    else
      System.out.println("Error!");
  }
}



Name:


To obtain the current delimiter pattern: Pattern delimiter( )

import java.io.IOException;
import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) throws IOException {
    Scanner src = new Scanner("1,2,3,4");
    src.useDelimiter(", *");
    System.out.println(src.delimiter());
  }
}



, *


Using Scanner: the complement of Formatter

  1. It reads formatted input and converts the input into the binary form.
  2. Scanner can read input from the console, a file, a string, or any source that implements the Readable interface or ReadableByteChannel.
  3. Scanner is packaged in java.util.

The following sequence creates a Scanner that reads the file test.txt:



import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) throws IOException {
    // Write output to a file.
    FileWriter fout = new FileWriter("test.txt");
    fout.write("2 3.4 5 6 7.4 9.1 10.5 done");
    fout.close();
    FileReader fin = new FileReader("Test.txt");
    Scanner src = new Scanner(fin);
    // Read and sum numbers.
    while (src.hasNext()) {
      if (src.hasNextDouble()) {
        System.out.println(src.nextDouble());
      }else{
        break;
      } 
    }
    fin.close();
  }
}



2.0
3.4
5.0
6.0
7.4
9.1
10.5


Using Scanner to read several different unknown types of data

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
  public static void main(String args[]) throws IOException {
    // Write output to a file.
    FileWriter fout = new FileWriter("test.txt");
    fout.write("int: 1  double 1.0  boolean true");
    fout.close();
    FileReader fin = new FileReader("Test.txt");
    Scanner src = new Scanner(fin);
    while (src.hasNext()) {
      if (src.hasNextInt()) {
        System.out.println("int: " + src.nextInt());
      } else if (src.hasNextDouble()) {
        System.out.println("double: " + src.nextDouble());
      } else if (src.hasNextBoolean()) {
        System.out.println("boolean: " + src.nextBoolean());
      } else {
        System.out.println(src.next());
      }
    }
    fin.close();
  }
}



int:
int: 1
double
double: 1.0
boolean
boolean: true


Using Scanner to receive user input

import java.util.Scanner;
public class MainClass{
  public static void main(String[] args){
    Scanner scanner = new Scanner (System.in);
    String s = scanner.next ();
    
    System.out.println(s);
  }
}