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

标签 java java.util.scanner

所以我试图从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/

相关文章:

java - Android:摩托罗拉 MC40 设备无法识别用于调试应用程序

java - 继续阅读数字,直到使用扫描仪到达换行符

Java Scanner 换行符用正则表达式解析(错误?)

java - 文件排序器 - fileNotFoundException

java - 如何减少 Full GC 的数量?

java 如何在十六进制转换中转义无法识别的字符

java - Scanner 类 hasNextInt() 方法似乎允许小数通过,或者可能是由其他原因引起的。

java - 使用 Scanner 从文件中读取 int 时出现 InputMismatchException

Java 到 PHP 的转换

java - 在 Java 应用程序中使用 ERB 模板的引用(通过 JRuby)