java tokenize从文本文件中读取的字符串

时间:2014-05-01 20:05:58

标签: java arraylist tokenize

我有这个程序从我的电脑读取文本文件。文本文件是标题列表。我试图弄清楚如何标记返回的内容,以便我得到全名而不是一块。我能找到的所有例子都涉及常规数组和Im使用arraylist。我需要能够将每个字符串读回我的arraylist并将其切断到&是

Text文件如下所示:

星球大战& DVD&安培;

指环王& DVD&安培;

生化危机& DVD&安培;

public static void main(String[] args) {

        File f = new File("file.txt");
        try {
            ArrayList<String> lines = get_arraylist_from_file(f);
            for (int x = 0; x < lines.size(); x++) {
                System.out.println(lines.get(x));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("done");

    }

    public static ArrayList<String> get_arraylist_from_file(File f)
            throws FileNotFoundException {
        Scanner s;
        ArrayList<String> list = new ArrayList<String>();
        s = new Scanner(f);
        while (s.hasNext()) {
            list.add(s.next());
        }
        s.close();
        return list;
    }

2 个答案:

答案 0 :(得分:1)

while (s.hasNextLine()) {
    list.add(s.nextLine().replaceAll("&", ""));
}

删除&符号

答案 1 :(得分:1)

     public static ArrayList<String> get_arraylist_from_file(File f) throws FileNotFoundException {
        Scanner scanner;
        ArrayList<String> list = new ArrayList<String>();
        scanner = new Scanner(f);
        String s = scanner.nextLine();

        while(scanner.hasNextLine()){
        String[] tempList = s.split("&"); //This will give you this [title][ DVD]
        String title = tempList[0];
        String type = tempList[1].subString(1); //If you want the input at the place of DVD, with the space removed
        list.add(title);
        s = scanner.nextLine();
        }
        scanner.close();
        return list;
}