如何读取txt文件并根据Java中的数字和字符串分隔文本

问题描述 投票:0回答:1

程序正在从文本文件读取。文本文件的每一行均以-2到2之间的数字开头。数字之后是一个句子。请参阅下面的txt文件的前三行:

1 Campanella gets the tone just right -- funny in the middle of sad in the middle of hopeful .
-2 Nothing more than an amiable but unfocused bagatelle that plays like a loosely-connected string of acting-workshop exercises .
1 It 's a sharp movie about otherwise dull subjects .

我有一个名为placeholder的类,其中包含以下字段:

public class placeholder implements Comparable<placeholder> {
    protected int score;
    protected String text;

    public placeholder(int score, String text) {
        this.score = score;
        this.text = text;
    }
}

我希望一种名为readFile的方法逐行进行,并将每一行存储到名为reviewsDB的列表中。列表中的每个对象的类型均为placeholder,行首的编号为score值,随后的单词为text值。我可以在以下区域中输入什么代码,以使数字和文本之间的每一行分开?

    public static List<placeholder> readFile(String filename) {

        File movieReviews = new File("reviews.txt");

        try {

            Scanner scanner = new Scanner(movieReviews);
            scanner.nextLine();

            List<placeholder> reviewsDB = new ArrayList<placeholder>();

            while (scanner.hasNextLine()) {
                int sentenceScore = 0;
                String sentenceText = null;

                //code to separate the number and text in each line here
                placeholder newSentence = new placeholder(sentenceScore, sentenceText);

                reviewsDB.add(newSentence);
            }

            return reviewsDB;
        }

        catch (Exception e) {

            System.out.println("Something went wrong");

            return null;
        }

    }
java list java.util.scanner
1个回答
0
投票

您可以使用Files.readAllLines(Path, Charset)获取代表文件内容的字符串列表。然后,您可以遍历列表并使用String.split(Regex, Limit)将字符串分成几部分。然后,您可以从零件中创建一个新的Placeholder-Object。

参见:

© www.soinside.com 2019 - 2024. All rights reserved.