使用java读取新行char

时间:2012-07-16 06:53:31

标签: java line newline

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

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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()方法只提供一行,你必须调用它直到有一个null(~C的EOF)

相关问题