簡體   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