我的文本文件中有 1,000 行数据,我希望每一行都有自己的 float []。
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
会导致:
float[0] = {1,1,1,1,1,1}
float[1] = {2,2,2,2,2,2}
float[2] = {3,3,3,3,3,3}
这可能吗?我只能找到将整个文件加载到数组中的示例。我尝试对所有数组进行硬编码,但超出了 ~65,000 的字节字符限制
最佳答案
尝试以下操作:
// this list will store all the created arrays
List<float[]> arrays = new ArrayList<float[]>();
// use a BufferedReader to get the handy readLine() function
BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
// this reads in all the lines. If you only want the first thousand, just
// replace these loop conditions with a regular counter variable
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String[] floatStrings = line.split(",");
float[] floats = new float[floatStrings.length];
for (int i = 0; i < floats.length; ++i) {
floats[i] = Float.parseFloat(floatStrings[i]);
}
arrays.add(floats);
}
请注意,我没有添加任何异常处理(例如 readLine(),抛出 IOException)。
关于Java 将每一行读入单独的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12523497/