英文:
Convert multiple lines of string into one string
问题
当我打印s时,它会输出:
what is coding
sky is green
ocean is gold
我该怎么做才能使其输出为:
what is coding sky is green ocean is gold
我已经尝试过 s.replace("\n\r", "")
和使用 System.lineSeparator()
,但都没有成功。
我做错了什么?
英文:
Let's say I have a code that reads each line of text from a text file and store it into a variable String s.
while (file.hasNext()){
String s = file.nextLine();
}
When I print s, it prints out
what is coding
sky is green
ocean is gold
What can I do to so that it prints out
what is coding sky is green ocean is gold
I've tried to do s.replace("\n\r", "") and using System.lineSeparator() but to no avail.
What am I doing wrong?
答案1
得分: 1
我希望你一切安好。
Scanner scanner = null;
String line = "";
try {
scanner = new Scanner(new File("D:\\ExampleFile.txt"));
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
while (scanner.hasNextLine()) {
// 这是你问题的关键。
line += scanner.nextLine();
}
System.out.println(line);
英文:
I hope you are fine.
Scanner scanner = null;
String line = "";
try {
scanner = new Scanner(new File("D:\\ExampleFile.txt"));
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
while (scanner.hasNextLine()) {
// This is the key for your problem.
line += scanner.nextLine();
}
System.out.println(line);
答案2
得分: 0
尝试
String fileWithoutNewLine = FileUtils.readFileToString(new File(<PATH_TO_FILE>)).replaceAll("\n", "");
英文:
Try
String fileWithoutNewLine = FileUtils.readFileToString(new File(<PATH_TO_FILE>)).replaceAll("\n", "")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论