【问题标题】:Is there any way to let the program recognize "\n" in text files as line break code?有没有办法让程序将文本文件中的“\n”识别为换行码?
【发布时间】:2018-08-29 15:56:21
【问题描述】:

我用 Java 创建游戏已经有一段时间了,我曾经直接在我的代码中编写所有游戏内文本,如下所示:

String text001 = "You're in the castle.\n\nWhere do you go next?"

但最近我决定将所有游戏内文本写入一个文本文件并尝试让程序读取它们并将它们放入一个字符串数组中,因为文本的数量增加了很多,这让我的代码难以置信长。除了一件事,阅读进展顺利。我在对话中插入了换行代码,虽然当我直接在我的代码中编写代码时代码可以正常工作,但当我尝试从文本文件中读取它们时,它们不再被识别为换行代码。

应该显示为:

You're in the castle.

Where do you go next?

但现在显示为:

You're in the castle.\n\nWhere do you go next?

代码不再将“\n”识别为换行代码。

代码如下:

import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        Scanner sc;
        StringTokenizer token;
        String line;
        int lineNumber = 1;
        String id[] = new String[100];
        String text[] = new String[100];

        try {
            sc = new Scanner(new File("sample.txt"));
            while ((line = sc.nextLine()) != null) {
                token = new StringTokenizer(line, "|");
                while (token.hasMoreTokens()) {
                    id[lineNumber] = token.nextToken();
                    text[lineNumber] = token.nextToken();
                    lineNumber++;
                }
            }
        } catch (Exception e) {
        }
        System.out.println(text[1]);
        String text001 = "You're in the castle.\n\nWhere do you go next?";
        System.out.println(text001);
    }
}

这是文本文件的内容:

castle|You're in the castle.\n\nWhere do you go next?
inn|You're in the inn. \n\nWhere do you go next?

如果有人告诉我如何解决这个问题,我将不胜感激。谢谢。

【问题讨论】:

  • 在文本文件中,\n 只是一个反斜杠,后跟一个n。它不是换行符。 \n 表示字符 0x0a 的约定仅适用于 Java 字符串或字符文字(以及一些其他语言)。
  • 这部分是文件的格式,需要对字符串内容进行自定义解析和处理。考虑一个可以定义 props 的属性文件,例如:locations=castle,innlocation.castle=You're in the castle.location.inn=You're in the inn.location.query=Where do you go next?。可以根据需要显示独立的属性值。
  • 除了 Java 属性文件之外,另一种标准文档格式是JSON。标准的优点是您可以使用一些库来代替编写自己的解析器。

标签: java string replace


【解决方案1】:

随便用

text[lineNumber] = token.nextToken().replace("\\n", "\n");

文本文件中的\n 本身并没有什么特别之处。它只是一个\,后面跟着一个\n

只有在 Java(或其他语言)中才定义此字符序列(在 char 或字符串字面量中)应被解释为 0x0a(ASCII 换行符)字符。

因此,您可以将字符序列替换为您希望将其解释为的字符序列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2015-07-27
    • 2019-12-08
    • 2017-10-25
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    相关资源
    最近更新 更多