簡體   English   中英

如何將文本文件拆分為兩個不同的數組?

[英]How Am I able to split a text file into two different arrays?

我有這個方法可以讀取文件並將其轉換為數組。 文本文件看起來像這樣,但文本文件中可以有任意數量的項目:

球 200
車20000
山羊 200

等等

我需要用 \n 分隔符分割每一行,用 \t 分隔符從數字中分割每個單詞,但我不確定用於實際分割它並將每個單詞添加到不同數組的語法(即球進入一個陣列,200 個進入另一個陣列)。 我想我可以在我擁有的方法中拆分每一行,但我不確定如何實現它。

編輯:這是一個類,我實際上不允許在程序中使用除數組之外的任何其他存儲系統。 :')

public static String[] readFile(String fileName) {
    try {
        
        Scanner fileScanner = new Scanner(new File(fileName));
        //Gets the length of the text file. How many lines there are.
        int wordCount = 0;
        while(fileScanner.hasNextLine()) {
            fileScanner.nextLine();
            wordCount++;
        }
        if(wordCount <= 0) 
            return null;
        
        //Creates an array using the length from the previous code.
        String[] finArr = new String[wordCount];
        fileScanner = new Scanner(new File(fileName));
        for(int i = 0; i <  finArr.length; i++) {
            if(!fileScanner.hasNextLine())
                break;
            finArr[i] = fileScanner.nextLine();
        }
        return finArr;
            
    }
    catch(IOException e) {
        System.out.println(e);
    }
    catch(Exception e) {
        System.out.println(e);
    }
    return null;
}
public static void main(String[] args) {
    String data = "Ball 200\nCar 20000\nGoat 200";
    List<String> words = new ArrayList<>();
    List<Integer> numbers = new ArrayList<>();
    
    try (BufferedReader reader = new BufferedReader(new StringReader(data))) {
        String line = reader.readLine();
        while (line != null) {
            String[] tokens = line.split("\\s");
            words.add(tokens[0]);
            numbers.add(Integer.parseInt(tokens[1]));
            line = reader.readLine();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println(words);
    System.out.println(numbers);
    //If you really need it as an array
    String[] arrWords = words.toArray(new String[]{});
    Integer[] arrNums = numbers.toArray(new Integer[]{});

    System.out.println(Arrays.toString(arrWords));
    System.out.println(Arrays.toString(arrNums));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM