繁体   English   中英

JAVA-如何读取特定行然后将其放入arraylist

[英]JAVA - how to read specific line then put it in arraylist

嗨,所以我有这个项目,要求我用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

我要做的就是将文本的左侧(好标题,金色,小麦,木材等)放入一个数组列表,并将文本的右侧(描述,闪亮的东西)放入另一个数组列表。 这是我当前的代码:

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.

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

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

这段代码是不正确的,因为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);

如果您愿意使用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级别。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM