JAVA - 如何阅读特定的行然后把它放在arraylist中

时间:2013-10-17 19:01:56

标签: java arraylist readfile java-io

嗨所以我有这个项目要求我在java中编写代码让我说我有这个txt文件:

GoodTitle   Description
Gold        The shiny stuff
Wheat       What wheaties are made of
Wood        To make more ships
Spices      To disguise the taste of rotten food
Tobacco     Smoko time
Coal        To make them steam ships go
Coffee      Wakes you up
Tea         Calms you down

我想要做的就是将文本的左侧(goodtitle,gold,wheat,wood等)放入arraylist和文本的右侧(描述,闪亮的东西)到另一个数组列表中。这是我目前的代码:

public void openFile(){
        try{
            x = new Scanner(new File("D://Shipping.txt"));
        }
        catch (Exception e){
            System.out.println("File could not be found");
        }
    }
    public void readFile(){
    while (x.hasNextLine()){
        String a = x.next();
        x.nextLine();
        ArrayList<String> list = new ArrayList<String>();
        while (x.hasNext()){
            list.add(x.next());
        }
        System.out.printf("%s \n", list);
        }
    }
    public void closeFile(){
        x.close();

可能需要对readFile进行一些修改,因为我仍然对如何做到这一点感到困惑。提前谢谢......

NOTE=I am not allowed to change the content of the txt file. 
     in my current code i still put the whole thing into 1 arraylist because i am unable to split them.

我需要使用String方法吗?因为我不知道该怎么做。 提前谢谢......

2 个答案:

答案 0 :(得分:0)

您必须将左侧读入一个列表,将右侧读入另一个列表。

此代码不正确,因为x.next()实际上并未返回一列。怎么知道一列是什么?但它应该让你知道如何做到这一点。

ArrayList<String> listL = new ArrayList<String>();
ArrayList<String> listR = new ArrayList<String>();
while (x.hasNextLine()){
    x.nextLine();
    if (x.hasNext()){
        listL.add(x.next());
    } else {
        listL.add("");
    }

    if (x.hasNext()){
        listR.add(x.next());
    } else {
        listR.add("");
    }
}
System.out.println(listL);
System.out.println(listR);

答案 1 :(得分:0)

如果您愿意使用Map<String, String>,也许您可​​以尝试这样的事情:

public static Map<String, String> getContents() throws IOException {
    final Map<String, String> content = new HashMap<>();
    final Scanner reader = new Scanner(new File("D://Shipping.txt"), "UTF-8");
    while(reader.hasNextLine()){
        final String line = reader.nextLine();
        final String[] split = line.split(" +");
        content.put(split[0], split[1]);
    }
    reader.close();
    return content;
}

public static void main(String args[]) throws IOException{
    final Map<String, String> content = getContents();
    content.keySet().forEach(k -> System.out.printf("%s -> %s\n", k, content.get(k)));
}

我只想指出,此解决方案是使用Java 8编程的,当然您可以将其修改为较低的JDK级别。