解析文本文件中的各种值 (Java)

Parsing various values in Textfile (Java)

我有一个这样的文本文件:

type = "Movie"
year = 2014
Producer = "John"
title = "The Movie"

type = "Magazine"
year = 2013
Writer = "Alfred"
title = "The Magazine"

我要做的是,首先在文件中搜索类型,在本例中为 "Movie" 或 "Magazine"。

如果是电影,则存储其下方的所有值,即 将 movie 变量设置为 2014,Producer 为 "John" 等

如果是Magazine类型,下面的所有变量也分开存放。

我目前的情况是这样的:

public static void Parse(String inPath) {
        String value;
        try { 
            Scanner sc = new Scanner(new FileInputStream("resources/input.txt"));

            while(sc.hasNextLine()) {
                String line = sc.nextLine();
                if(line.startsWith("type")) {
                    value = line.substring(8-line.length()-1);
                    System.out.println(value);

                }

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(LibrarySearch.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

但是,我在简单地打印第一种类型 "Movie" 时遇到了问题。我的程序似乎跳过了那个,而是打印出 "Magazine"。

仅针对此问题,是否因为行:line.startsWith("type")正在检查文件中的当前行是否以 type 开头,但由于名为 line 的实际字符串是设置为下一行,它会跳过第一个 "type"?

此外,解析类型 "Movie""Magazine" 下的实际值(等号右侧)的最佳方法是什么?

我建议您尝试以下操作:

BufferedReader reader = new BufferedReader(new FileReader(new File("resources/input.txt")));

String line;

while((line = reader.readLine()) != null) {

    if (line.contains("=")) {
        String[] bits = line.split("=");
        String name = bits[0].trim();
        String value = bits[1].trim();

        if (name.equals("type")) {
            // Make a new object
        } else if (name.equals("year")) {
            // Store in the current object
        }
    } else {
        // It's a new line, so you should make a new object to store stuff in.
    }
}

在你的代码中,我觉得子字符串很可疑。如果您根据等号进行拆分,那么它应该更有弹性。