【发布时间】:2013-08-19 07:39:32
【问题描述】:
我在 java 中读取文件时遇到问题: 例如,我有一个这样的文件:
2,3
2
5
2
3
4
其中第一行表示2个数组A和B的长度,另一行是每个数组的元素,所以:A[2,5] B[2,3,4]。我可以读取这个输入并保存到两个数组中
public static void main(String[] args) throws IOException{
int A[] = null;
int B[] = null;
//int C[] = null;
//int k = 0;
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine = br.readLine(); // step 1
if (strLine != null) {
String[] delims = strLine.split(","); // step 2 split first line
// step 3 initialization array A and B
A = new int[Integer.parseInt(delims[0])];
B = new int[Integer.parseInt(delims[1])];
//C = new int[Integer.parseInt(delims[2])]; //PROBLEMA SE NON CE K DA ERRORE RISOLVERE
//k = 0;
//k = C.length;
// step 4 Load A element from file input
for (int i = 0; i < A.length; i++)
A[i] = Integer.parseInt(br.readLine());
// step 5 load B element form file input
for (int i = 0; i < B.length; i++)
B[i] = Integer.parseInt(br.readLine());
br.close();
}// step 6
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
//Sort Array with MergeSort
System.out.println(Arrays.toString(A));
System.out.println(Arrays.toString(B));
但我的问题是输入可能在第一行有另一个我必须保存的元素 k。
2,3,5
2
5
2
3
4
和 A[2,5] B[2,3,4] 我想保存 k = 5 但我不知道该怎么做。问题是 K 可能不在输入中。 提前致谢
【问题讨论】:
-
你已经尝试了什么?
-
@user1841492:你可以删除问题meta.stackexchange.com/questions/42265/…
-
请不要破坏您的问题。你为什么取消删除帖子只是为了删除问题?如果您现在想删除您的帖子,您必须将其标记为版主。
-
请不要对文本使用 DataInputStream。
标签: java bufferedreader