开发者

Reading variable number of lines from file

开发者 https://www.devze.com 2023-03-22 09:24 出处:网络
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

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消