How do I read multiple lines (in Java) from an input file (say, helloworld.in)?
The input fi开发者_运维知识库le does not have a fixed number of lines, it can have anywhere from 3 to 99999 lines.
Use a java.util.Scanner:
Scanner scanner = new Scanner(new File("helloworld.in"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
// Do something
}
With a scanner, you can also read specific types, eg scanner.nextInt() etc
You can use the file stream and buffer stream.
public static void main(String[] args) {
// TODO Auto-generated method stub
int ch=0;
File tempFile=new File("/tmp/apple");
try{
BufferedReader filer=new BufferedReader(new FileReader(tempFile));
while( (ch=filer.read())!= -1)
System.out.printf("%c",ch);
}
catch(FileNotFoundException e){
e.printStackTrace(System.err);
}
catch(IOException e){
e.printStackTrace(System.err);
}
}
Use java.io.BufferedReader for less overhead.
BufferedReader reader = new BufferedReader(new FileReader(new File("file.txt")));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
精彩评论