gpt4 book ai didi

java - 为什么文本文件没有完全读取?

转载 作者:行者123 更新时间:2023-12-02 05:59:14 24 4
gpt4 key购买 nike

所以我试图从txt文件中提取一段代码,该代码的开头由“# EMPIRES”指示,结尾由另一个以“#”开头的字符串指示。然而,我的程序永远找不到该片段的开头,并继续前进,直到到达文件末尾。

为了尝试找出问题所在,我首先尝试打印它找到的每一行。而在这里我遇到了另一个问题。我的代码很久以前就已经停止寻找新行了甚至达到了“# EMPIRES”。

    public String getEmpirestxt(String fileName) {
Scanner sc;
try {
sc = new Scanner(new File(fileName));
String currentLine = sc.nextLine();
StringBuilder empiresText = new StringBuilder(currentLine);
while (!currentLine.startsWith("# EMPIRES")) {
currentLine = sc.nextLine();
System.out.println(currentLine);
}
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
return empiresText.toString();
} catch (FileNotFoundException ex) {
System.out.println("Landed_Titles.txt not found.");
}
return null;
}

文本文件本身: https://www.wetransfer.com/downloads/a1093792d5ac54b6ccce04afecb9357f20140402095042/505fca

最佳答案

这是我对您问题的解决方案。我使用 newBufferedReader 而不是 Scanner 来读取文件。此示例适用于 Java 7。

public String getEmpirestxt2(String fileName) {
Charset charset = Charset.forName("ISO-8859-1");
Path filePath = Paths.get(fileName);
try (BufferedReader reader = Files.newBufferedReader(filePath, charset)) {
String line = null;

// find the start of the piece
while ((line = reader.readLine()) != null && !line.equals(START)) {
}
System.out.println("START: " + line);

// getting the piece
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null && !line.startsWith(END)) {
sb.append(line);
}
System.out.println("END: " + line);

return sb.toString();
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
return null;
}

该方法中的常量是:

private static final String START = "# EMPIRES";
private static final String END = "#";

我用你的文件测试了它,它工作正常。它还打印所需片段的起点和终点:

START: # EMPIRES
END: # color={ 144 80 60 }

关于java - 为什么文本文件没有完全读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22807698/

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