reading input till EOF in java

后端 未结 10 631
后悔当初
后悔当初 2020-12-09 06:35

In C++ if I wish to read input till the EOF I can do it in the following manner

while(scanf(\"%d\",&n))
{
    A[i]=n;
    i++;
}

I can

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 06:44

    Here is Java equivalent code using BufferedReader and FileReader classes.

      import java.io.BufferedReader;
      import java.io.FileReader;
      import java.io.IOException;
    
      public class SmallFileReader {
            public static void main(String[] args) throws IOException {  
    

    Option 1:
    String fileName = args[0];
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    Option 2:
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter a file name: ");
    String fileName = br.readLine();

                 //BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
                 String line=null;
                 while( (line=br.readLine()) != null) {
                        System.out.println(line);  
                 }
      }
    }  
    

    I made little modification to @Vallabh Code. @tom You can use the first option, if you want to input the file name through command line.
    java SmallFileReader Hello.txt
    Option 2 will ask you the file name when you run the file.

提交回复
热议问题