[英]Read txt and save into array,java
在用Java读取文件并将每个元素保存到2个数组中时遇到一些问题。 我的txt是这样写的
2,3
5
4
2
3
1
其中第一行是两个数组A = 2和B = 3的长度,然后是每个数组的元素。 我不知道如何将它们保存到A和B中,并使用它们的长度来初始化数组。 最后,每个数组将为A = [5,4] B = [2,3,1]
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("prova.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != " ") {
String[] delims = strLine.split(",");
String m = delims[0];
String n = delims[1];
System.out.println("First word: "+m);
System.out.println("First word: "+n);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
这就是我做的..我使用System.out.println ....只是在控制台中打印是没有必要的。有人可以帮助我,给我一些建议吗? 提前致谢
同样,将大问题分解为小步骤,解决每一步。
将此答案与@Hovercraft答案中概述的步骤进行匹配
String strLine = br.readLine(); // step 1
if (strLine != null) {
String[] delims = strLine.split(","); // step 2
// step 3
int[] a = new int[Integer.parseInt(delims[0])];
int[] b = new int[Integer.parseInt(delims[1])];
// step 4
for (int i=0; i < a.length; i++)
a[i] = Integer.parseInt(br.readLine());
// step 5
for (int i=0; i < b.length; i++)
b[i] = Integer.parseInt(br.readLine());
br.close(); // step 6
// step 7
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
注意,我叫br.close()
。 使用in.close()
可以仅关闭内部流,而BufferedReader
仍保持打开状态。 但是关闭外部包装流会自动关闭所有包装的内部流。 请注意,这样的清理代码应始终放在finally
块中。
同样,也不需要链中有DataInputStream
和InputStreamReader
。 只需将BufferedReader
直接包装在FileReader
周围即可。
如果所有这些课程都让您有些困惑; 请记住, Stream
类用于在字节级别进行读取,而Reader
类用于在字符级别进行读取。 因此,您在这里只需要Reader
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.