从制表符分隔的.text文件中读取值

时间:2014-04-25 18:36:17

标签: java.util.scanner

我正在尝试从制表符分隔的文本文件中读取值并将它们存储到ArrayLists中。问题在于某些值(例如种族和帮派)可能包含由单个空格分隔的多个字符串。有没有办法让它可以读到所有字符串,直到下一个标签?提前谢谢。

while (file.hasNext()) // creates while loop using scanner, in that will
                            // store values in arraylist until it runs out
                            // of values
    {
        // stores values from tab delimited file in specified variable each
        // time the while loop is run
        serial = file.next();
        last = file.next();
        middle = file.next();
        first = file.next();
        soc = file.next();
        birth = file.next();
        ethnicity = file.next();
        height = file.next();
        weight = file.next();
        gang = file.next();
        reason = file.next();
        dateIn = file.next();
        dateOut = file.next();
        parole = file.next();
        cell = file.next();

        // stores values from variables above in the defined array list
        serialList.add(i, serial);
        lastList.add(i, last);
        middleList.add(i, middle);
        firstList.add(i, first);
        socList.add(i, soc);
        birthList.add(i, birth);
        ethnicityList.add(i, ethnicity);
        heightList.add(i, height);
        weightList.add(i, weight);
        gangList.add(i, gang);
        reasonList.add(i, reason);
        dateInList.add(i, dateIn);
        dateOutList.add(i, dateOut);
        paroleList.add(i, parole);
        cellList.add(i, cell);
        i++; // increases value each time loop runs
    }

2 个答案:

答案 0 :(得分:1)

假设您的文件也是行分隔的。你应该逐行阅读文件。

fis = new FileInputStream("the_file_name");
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
while ((line = br.readLine()) != null) {
     values = line.split("\t");
     serial = values[0];
     last = values[1];

     ...
 }

如果要获取所有以空格分隔的值的数组,请调用values[6].split(" ");

答案 1 :(得分:0)

next方法可以选择将字符串作为参数。字符串是您想要获得的模式,因此您需要类似以下内容的

String s = file.next("[\\S ]+");

其中说抓住任何一组非白色空间或空间。