首页 > 解决方案 > 如何将文本文件的行读入JavaFx中的数组

问题描述

我需要帮助阅读文本文件的内容并将每一行保存为数组中的字符串。例如,文本文件包含以下数据:

°C
12,0
21,9

我想将每一行读入一个数组,如:

line[0] = first_ine; //°C
line[1] = secondLine; //12,0
line[2] = thirdLine; //21,9

我的目标是能够访问我存储在数组中的任何行并将其内容打印在标签上,例如:

labelWithText.setText(line[0]);

行。这是我的代码的一个版本,我在其中尝试使用数组将文本文件的每一行存储在数组字段中。它会导致 ArrayOutOfBound 错误。

try {
    input = new FileInputStream(new File("DataFiles/myData.txt"));

    CharsetDecoder decoder = Charset.forName("ISO-8859-1").newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    InputStreamReader reader = new InputStreamReader(input, decoder);

    BufferedReader buffReader = new BufferedReader(reader);         
    StringBuilder stringBuilder = new StringBuilder();
    String line = buffReader.readLine();

    int i = 0;
    String lineContent[] = line.split("\n");

    while(line != null) {
        stringBuilder.append(line).append(System.getProperty("line.separator"));
        line = buffReader.readLine();

        lineContent[i] = line;
        i++;
    }

    buffReader.close();         

    nomDataLabel.setText(lineContent[0]);
    minDataLabel.setText(lineContent[1]);
    maxDataLabel.setText(lineContent[2]);
} catch (Exception e) {
    e.printStackTrace();
}

标签: javaarraysjavafx

解决方案


平均 Joe 这里有两种加载 dictionary.txt 文件的方法
一种将数据放在 String[] 中,将另一种放在 ArrayList 字典
中 附带说明 Buffered Reader 比 Scanner 方法快 6 到 9 倍

对于数组列表:

ArrayList<String> dictionary = new ArrayList<>();

private void onLoad() throws FileNotFoundException, IOException {
    long start2 = System.nanoTime();

    try (BufferedReader input = new BufferedReader(new FileReader("C:/A_WORDS/dictionary.txt"))) {
        for (String line = input.readLine(); line != null; line = input.readLine())
            dictionary.add(line);

        input.close();
    }

对于一个简单的数组:

String[] simpleArray;

private void loadFile() throws FileNotFoundException, IOException {
    File txt = new File("C:/A_WORDS/dictionary.txt");
    try (Scanner scan = new Scanner(txt)) {
        data = new ArrayList<>() ;
        while (scan.hasNextLine())
            data.add(scan.nextLine());

        simpleArray = data.toArray(new String[]{});
        int L = simpleArray.length;
        System.out.println("@@@ L "+L);
    }
}

推荐阅读