0

我想导入任何 .txt 文件(请注意 .txt 文件在一列中有 3 组数字;每组用空格分隔)

2   
3    
4   

3   
2   
1  

1   
2  
3   

并将一组数字转换为数组。(数组 1、2 和 3)

array1[] = {2,3,4}   
array2[] = {3,2,1}   
array3[] = {1,2,3}

然后能够在 JFreeGraph 库中绘制数组,这就是我开始的方式......我正在使用 netbeans 和 java Swing

   @Action
public void openMenuItem() {

    int returnVal = jFileChooser1.showOpenDialog(null);     
    if (returnVal == JFileChooser.APPROVE_OPTION) {  
        File file = jFileChooser1.getSelectedFile();

    try {
    FileReader fileReader = new FileReader(file);    
            jTextArea2.read(new FileReader(file.getAbsolutePath()), null);         

        } catch (IOException ex) {
            System.out.println("problem accessing file" + file.getAbsolutePath());
        }
    } else {
        System.out.println("File access cancelled by user.");
    }
}
4

1 回答 1

2

逐行读取文件,可能使用BufferedReaderreadLine。一旦你遇到一个空行 - 你有一组新的数字。这是一个过于简化的示例,它维护一个列表列表,并且只读取字符串:

public static List<List<String>> parseFile(String fileName){
    BufferedReader bufferedReader = null;
    List<List<String>> lists = new ArrayList<List<String>>();
    List<String> currentList = new ArrayList<String>();
    lists.add(currentList);

    try {
        bufferedReader = new BufferedReader(new FileReader(fileName));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.isEmpty()){
                currentList = new ArrayList<String>();
                lists.add(currentList);
            } else {
                currentList.add(line);
            }
        }

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (bufferedReader != null)
                bufferedReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return lists;
}

编辑:使用带有 JTextArea 的结果列表

List<List<String>> lists = parseFile("test.txt");
for (List<String> strings : lists){
    textArea.append(StringUtils.join(strings, ",") + "\n");
    System.out.println(StringUtils.join(strings, ","));
}
于 2012-04-14T20:36:56.510 回答