1

帮助伙计们,我刚刚在网上看到了这个例子。我想用它来精确打印包含新行的相同格式的文本文件的内容,但它只打印出第一行。谢谢

 import java.util.*;
 import java.io.*;

      public class Program
      {
          public static void main(String[] args)throws Exception
          {
          Scanner scanner = new Scanner(new FileReader("B:\\input.txt"));
          String str = scanner.nextLine(); 

          // Convert the above string to a char array.
          char[] arr = str.toCharArray();

          // Display the contents of the char array.
          System.out.println(arr);
          }
      }
4

2 回答 2

3

试试这个..按原样阅读整个文件......

File f = new File("B:\\input.txt");
FileReader fr = new FileReader(f);
BufferedReader br  = new BufferedReader(fr);

String s = null;

while ((s = br.readLine()) != null) {
    // Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}

br.close();

但是,如果您想使用 Scanner,请尝试此....

while ( scan.hasNextLine() ) {
    str = scan.nextLine();
    char[] arr = str.toCharArray();
}
于 2012-07-16T06:58:34.530 回答
2
public class Program {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(new FileReader("B:\\input.txt"));
        String str;
        while ((str = scanner.nextLine()) != null)
            // No need to convert to char array before printing
            System.out.println(str);
    }
}

nextLine() 方法只提供一行,你必须调用它直到有一个空(~C 的 EOF)

于 2012-07-16T06:55:50.543 回答