[英]Is there a way for Java Scanner to include '\n' when it is reading lines?
java.util.Scanner
從文件中讀取時有什么辦法可以包含換行符轉義符嗎?
這是我的代碼:
File myFile = new File("file.txt");
Scanner myReader = new Scanner(myFile);
String content = "";
while(myReader.hasNextLine()) {
content += myReader.nextLine();
}
System.out.println(content);
myReader.close();
當它從文件中讀取時,它不包含 '\\n' 或任何新行。 有誰知道如何做到這一點?
謝謝
當它從文件中讀取時,它不包含 '\\n' 或任何新行。 有誰知道如何做到這一點?
您可以按如下方式顯式添加新行:
while(myReader.hasNextLine()) {
content += myReader.nextLine() + "\n";
}
我還建議您使用StringBuilder
而不是String
來追加循環。
StringBuilder content = new StringBuilder();
while (myReader.hasNextLine()) {
content.append(myReader.nextLine()).append(System.lineSeparator());
// or the following
// content.append(myReader.nextLine()).append('\n');
}
如果您只想讀取行和行終止符,您可以通過更改Scanner.next()
的行為來實現。 如果您運行以下命令,它將把行和新行終止符作為一個單位。
\\\\z
是一個正則表達式指令,表示包含行終止符。Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z");
for (int i = 0; i < 5; i++) {
String line = scan.next();
System.out.println(line + "on next line");
}
要從文件中讀取,請嘗試此操作。
try {
Scanner scan = new Scanner(new File("f:/Datafile.txt"));
scan.useDelimiter("\\z");
while (scan.hasNextLine()) {
String line = scan.next();
System.out.print(line);
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.