英文:
How to read “\n” text in file as a newline?
问题
这一行用于测试。
测试测试测试。
以下是我在Java中读取这行内容的方式:
```java
import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
class Main {
public static void main(String[] args) {
List<String> list = null;
try {
list = Files.readAllLines(Paths.get("文本文件路径"));
} catch (IOException e) {
e.printStackTrace();
}
String[] Array = list.toArray(new String[list.size()]);
}
}
当我使用System.out.print(Array[0]);
进行输出时,我得到以下结果:这一行用于测试。\n测试测试测试。
我希望结果如下所示:
这一行用于测试。
测试测试测试。
<details>
<summary>英文:</summary>
My text file contains this 1 line
```This line is used for testing.\nTesting testing testing.```
And this is how I read that line in Java
import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
class Main {
public static void main(String[] args) {
List<String> list = null;
try {
list = Files.readAllLines(Paths.get("path to txt file"));
} catch (IOException e) {
e.printStackTrace();
}
String[] Array = list.toArray(new String[list.size()]);
}
}
And when I print it out with System.out.print(Array[0]); I get this as a result: ```This line is used for testing.\nTesting testing testing.```
I want the result to be like this:
```This line is used for testing.```
```Testing testing testing.```
</details>
# 答案1
**得分**: 1
如果您想要这样的行为,最好的方法是在您的代码中实现它:
```java
list = Files.readAllLines(Paths.get(""))
.stream()
.flatMap(line -> Arrays.stream(line.split("\\n")))
.collect(Collectors.toList());
这段代码会读取文件,就像您之前所做的一样,并将\n
解释为新的换行符。这是我找到的唯一方法。
英文:
If you want such behavior, the best way is to implement this in your code:
list = Files.readAllLines(Paths.get(""))
.stream()
.flatMap(line -> Arrays.stream(line.split("\\\\n")))
.collect(Collectors.toList());
This read the files, like you did, plus it interprets the \n
to give you new Lines every time.
That's the only way I've found
答案2
得分: 0
Sure, here is the translation of the provided text:
在文本文件中键入\n
并不会产生换行,而是会产生单独的字符\
和n
。如果您想要添加换行,并使您的程序打印出带有该换行的文本,您需要实际插入换行(即按下回车键)。
如果您希望使您的程序能够理解转义字符(将\n
处理为换行符),您需要自己添加该逻辑。最简单的方法是遍历每个字符,如果一个字符是\
,则根据下一个字符进行处理。在您的情况下,一旦您看到\
后跟着n
,请删除这两个字符并在其位置插入换行。
英文:
Typing \n
in a text file doesn't give you a newline, it gives you the individual characters \
and n
. If you want to add a newline and have your program print out the text with that newline, you'll have to actually insert a newline (ie. press enter).
If you want to make your program be able to understand escaped characters (process \n
as a newline), you'd have to add that logic yourself. The simplest way would be to iterate over each character and if a character is \
, process according to the next character. In your case, once you see \
followed by n
, delete those two characters and insert a newline in their place.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论