gpt4 book ai didi

Java - List 打印\n 而不是显示换行符

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:51 24 4
gpt4 key购买 nike

我有一个 .txt 文件阅读器,它读取文件的各个行并将它们存储在 List<String> 中然后我将其显示在 JTextArea 上。有些行包含 \n ,因为我想在显示时进行特定的中断。但是,当我显示代码时,\n显示而不是像通常那样断线。

我尝试替换 \n通过放置代码 str.replaceAll( "\\\\n", System.lineSeperator()); 来换行在 while 循环中,list.add(str); 之前但似乎没有任何效果。

重申一下,我只需要一种方法来更改 \n到换行符。任何帮助将不胜感激。

.txt 阅读器的代码如下。

static void parseStringArray(final String filePath, List<String> list){
try {
InputStream input = Text.class.getResourceAsStream(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String str;
while((str = reader.readLine()) != null){
list.add(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}

**编辑 - 我已更新该帖子以包含更多代码。

我作为参数发送的列表在方法之前初始化。这是

protected static List<String> textfiles = new ArrayList<String>();

.txt 文件中的一行示例为

欢迎!\n\n如果您想继续,请输入下面的密码。\n祝您住宿愉快!

显示此文本的代码如下。 (请原谅格式)

Timer teletypeTimer = null;
public static void animateTeletype(final JTextArea displayArea)
{
final String[] s = new String[1];
s[0] = "";
final int[] i = new int[2];
i[0] = 0;
i[1] = 0;
teletypeTimer = new Timer(20, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(i[0]==0)
displayArea.setText("");
s[0] = TTqueue[i[1]].substring(i[0], i[0]+1);
i[0]++;
displayArea.append(s[0]);
if(displayArea.getText().equals(TTqueue[i[1]]))
{
i[1]++;
if(TTqueue[i[1]] !=null)
{
teletypeTimer.stop();
i[0] = 0;
timerRestart(5000, teletypeTimer);
}
else
{
Arrays.fill(TTqueue, null);
complete=true;
teletypeTimer.stop();
}
}
}
});
teletypeTimer.start();
}

最佳答案

(代表 OP 发布)

我将 replaceAll() 替换为 replace(),并研究了 Pshemo 和 Nick Vanderhoven 的观点。我按照 Pshemo 的建议添加了代码行 str = str.replace("\\n", System.lineSeparator()); ,这样就完成了。干杯!

关于Java - List<String> 打印\n 而不是显示换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40826246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com