[英]Reading textfile into 2d array JAVA
I am trying to read a given text file filled with a bunch of doubles, the text file looks something like this(no spaces between each line): 我正在尝试读取给定的文本文件,其中包含一堆双打,文本文件看起来像这样(每行之间没有空格):
0, 0.007133248, 0.003747135, 0.0034464097, 0.009517824, 0.0036065334, 0.007921185, 0.0041013476 0,0.007133248,0.003747135,0.0034464097,0.009517824,0.0036065334,0.007921185,0.0041013476
1, 0.006223865, 5.804103E-4, 5.6967576E-4, 0.008850083, 0.003269921, 3.7322243E-4, 0.0011008179 1,0.006223865,5.804103E-4,5.6967576E-4,0.008850083,0.003269921,3.7322243E-4,0.0011008179
2, 0.0051101227, 0.008973722, 0.0013274436, 0.00922496, 0.0050817304, 0.004631279, 0.0069321943 2,0.0051101227,0.008973722,0.0013274436,0.00922496,0.0050817304,0.004631279,0.0069321943
essentially 1000 rows with 8 columns, and am trying to turn this into a 2d array of data[1000][8], am having trouble iterating through the data though. 本质上是1000行8列,并且试图将其转换为data [1000] [8]的二维数组,但是在遍历数据时遇到了麻烦。 Heres what I have so far, any help would be appreciated! 这是我到目前为止所拥有的,任何帮助将不胜感激!
public static void readFile2() throws IOException{
Double[][] data = new Double[1000][8];
int row = 0;
int col = 0;
Scanner scanner = null;
scanner = new Scanner(new BufferedReader(new FileReader("/Users/Roman/Documents/workspace/cisc124/Logger (1).csv")));
while (scanner.hasNext() && scanner !=null) {
scanner.useDelimiter(",");
while(row<data.length && col<8){
data[row][col] = Double.parseDouble(scanner.next());
col++;
//System.out.print(Arrays.deepToString(data));
}
col=0;
row++;
}
System.out.println(Arrays.deepToString(data));
scanner.close();
}
It would be more convenient reading thefile line by line.. 逐行读取文件会更方便。
String[] data = new String[1000];
int row = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf-8"));
String line;
while ((line = br.readLine()) != null) {
data[row]= line;
row++;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
and at the end do the same 最后做同样的事情
System.out.println(Arrays.ToString(data));
or if you need the element at a given index then split a row and use Double.parse();
或者如果您需要给定索引处的元素,则拆分一行并使用Double.parse();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.