java - 有没有办法让程序将文本文件中的“\n”识别为换行码?
问题描述
我用 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?
如果有人告诉我如何解决这个问题,我将不胜感激。谢谢你。
解决方案
只需使用
text[lineNumber] = token.nextToken().replace("\\n", "\n");
文本文件本身并没有什么特别之处\n
。它只是一个\
,后面跟着一个\n
。
只有在 Java(或其他语言)中才定义此字符序列 - 在 char 或字符串文字中 - 应被解释为0x0a
(ASCII 换行符)字符。
因此,您可以将字符序列替换为您希望将其解释为的字符序列。
推荐阅读
- html - 我在容器背景和前景中有 2 个图像。如何使前景图像响应
- function - LISP 编写一个名为 cut-in-half 的函数,它接收一个列表并创建一个新列表,其元素是前半部分和后半部分
- php - Laravel 5.7,雄辩:此集合实例上不存在属性 [X],多对多关系
- ios - 绘制半径等于手指路径的圆
- ruby-on-rails - Zeitwerk,require_dependency 并将 Ruby 类拆分为几个文件
- excel - excel,合并静态列和数字列表之间的两列
- asciidoc - 链接到 asciidoc 中同一页面的部分
- ads - 无自动化接口的 TwinCAT 3.0 广播搜索
- javascript - 如何更新这样的嵌套状态?
- google-app-engine - app.yaml 中的用户 error_handlers 以返回 HTTP 响应