简体   繁体   English

如何将文本文件拆分为两个不同的数组?

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

I have this method which reads the file and converts it into an array.我有这个方法可以读取文件并将其转换为数组。 The text file looks something like this, but there can be any number of items on the text file:文本文件看起来像这样,但文本文件中可以有任意数量的项目:

Ball 200球 200
Car 20000车20000
Goat 200山羊 200

etc.等等

I need to split each line with a \n delimiter and each word from the number with a \t delimiter, but I'm not sure the syntax to use to actually split it that way and add each one to a different array (ie ball goes into one array and 200 goes into another).我需要用 \n 分隔符分割每一行,用 \t 分隔符从数字中分割每个单词,但我不确定用于实际分割它并将每个单词添加到不同数组的语法(即球进入一个阵列,200 个进入另一个阵列)。 I figured I could split each line inside of the method I have, but I was not sure how to implement it.我想我可以在我拥有的方法中拆分每一行,但我不确定如何实现它。

EDIT: This is for a class and I'm not actually allowed to use any other storage system in the program besides arrays.编辑:这是一个类,我实际上不允许在程序中使用除数组之外的任何其他存储系统。 :') :')

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