java 使用java读取换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11499398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading new line char using java
提问by Tokuchi Toua
Help guys, i've just seen this example in the web. i would like to use this to print exactly the contents of a text file in the same format containing new lines, but it just prints out the first line. thanks
帮帮忙,我刚刚在网上看到了这个例子。我想用它以包含新行的相同格式准确打印文本文件的内容,但它只是打印出第一行。谢谢
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);
}
}
回答by Kumar Vivek Mitra
Try this.. To read the whole file as it is.....
试试这个.. 按原样读取整个文件.....
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();
But still if you want to use Scanner then try this....
但是如果你想使用扫描仪,那么试试这个......
while ( scan.hasNextLine() ) {
str = scan.nextLine();
char[] arr = str.toCharArray();
}
回答by NiziL
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);
}
}
The nextLine() method provides only one line, you must call it until have a null ( ~ C's EOF )
nextLine() 方法只提供一行,你必须调用它直到有一个空值(~C 的 EOF)