当我们不知道文件中的行数时,是否有可能从文件中读取数据并将其存储到2d数组中

时间:2015-02-19 13:20:20

标签: java arraylist

我必须从文件Here is data读取数据,并希望为每个模型绘制图表与厚图(数据中的第1列)和alpha(第3列)。每个模型都有7个行数据,最后一个从0开始不需要。这是我的代码。它有效,但我认为它不是很好的代码。请给我更好的方法来做同样的事情。

public class readFile {

public static int showLines(String fileName)  {
    String line;
    int currentLineNo = 0;
    BufferedReader in = null;
    try {
        in = new BufferedReader (new FileReader(fileName));

        //read until endLine
        while(((line = in.readLine()) != null)) {

            if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
                //skipping the line that start with M, # and 0.
                currentLineNo++;
            } 
        }   
    } catch (IOException ex) {
        System.out.println("Problem reading file.\n" + ex.getMessage());
    } finally {
        try { if (in!=null) in.close(); } catch(IOException ignore) {}
    }
    return currentLineNo;
}

//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow)  {
    String line;
    String temp []=null;
    String data [][]=new String[numRow][10];
    int i=0;


    BufferedReader in = null;
    try {
        in = new BufferedReader (new FileReader(fileName));

        //read until endLine
        while(((line = in.readLine()) != null)) {
            if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {

                    temp=(line.trim().split("[.]"));
                    for (int j = 0; j<data[i].length; j++) {    
                        data[i][j] =temp[j];
                    }
                    i++;
                }
            }
        // Extract one column from 2d matrix
        for (int j = 0; j <numRow; j=j+6) {
            for (int j2=j; j2 <6+j; j2++) {
                System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));  
                //6 element of every model, col1 and col3
                // will add to dataset.
            }
        }

    } catch (IOException ex) {
        System.out.println("Problem reading file.\n" + ex.getMessage());
    } finally {
        try { if (in!=null) in.close(); } catch(IOException ignore) {}
    }
}

//Main Method
public static void main(String[] args) {
    //System.out.println(showLines("rf.txt"));
    readData("rf.txt",showLines("rf.txt") );

}

}

1 个答案:

答案 0 :(得分:0)

如johnchen902暗示使用列表

List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
    input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
    String[] parts = string.split("-");
    for (int k=0;k<n;k++){
        data[i][k]=parts[k];
    }
}

类似的东西

希望它有所帮助。 PLZ更加努力地提出这个问题。给我们提供所需的输入文件,以及您现在提出的用于自行解决问题的代码。

相关问题