[英]How to read in 1 specific column of a txt file and store into an Array or ArrayList [Java]
[英]Java Reading a txt that has different numbers in its column file and store data in an arraylist
大家好,我在下面有一個 txt 文件,我需要存儲第二列數據,但它給了我一個錯誤,因為有些行有 1,有些有 2,有些每行有 3 個輸入。 我該如何解決這個問題?
5
3 4
3 4
3 3
3 4
3 3
3 4
3 3
3 2
3 4
3 3
3 2
3 1
3 4
3 3
3 2
3 1
3 0
1
2
5 3 4
3 4
3 4
3 3
3 4
3 3
3 4
3 3
3 2
3 4
3 3
3 2
3 1
3 4
3 3
3 2
3 1
3 0
1
2
5 4 6
4 4
4 4
4 4
4 4
4 4
4 4
4 3
4 3
4 3
4 3
4 4
4 4
1
2
5 4 6
0
這就是我所做的,我試圖區分大小和其他方式,但仍然無法得到答案......
String line = "";
ArrayList<String> numbers= new ArrayList<String>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("input1.txt"));
int n = 0;
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split(" ");
int size = arr.length;
List<String> list = ConvertToList.convertArrayToList(arr);
List<Integer> listOfInteger = convert.convertStringListToIntList(list, Integer::parseInt);
if (list.size() == 2) {
line.split("\\s+");
numbers.add(line.split("\\s+")[0]);
System.out.println(numbers);
}
}
} catch(Exception e) {
e.printStackTrace();
}
您無需再次拆分線路。 第一次拆分行時,檢查結果數組的長度是否為2
。 如果是,請將arr[1]
添加到numbers
。
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split(" ");
if (arr.length >= 2) {
numbers.add(arr[1]);
System.out.println(numbers);
}
}
根據您的評論,我為您提供以下使用您的列表的代碼:
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split(" ");
List<String> list = ConvertToList.convertArrayToList(arr);
List<Integer> listOfInteger = convert.convertStringListToIntList(list, Integer::parseInt);
if (listOfInteger.size() >= 2) {
numbers.add(listOfInteger.get(1));
}
}
System.out.println(numbers);
您可以保留System.out.println(numbers);
在while
循環內部或外部,具體取決於您要如何打印numbers
。
如果您只想讀取和保存第二列而不是使用索引 1 獲取第二列中的數據。(在您的 while 循環之后。)
String secondCol = sCurrentLine.split(" ")[1];
如果您在 2 列中沒有值,則會拋出異常,您應該使用簡單的 try catch 處理。 最后將其轉換為 int 並存儲在您的列表中。 與以下。
listOfInteger.add(Integer.parseInt(secoundCol));
希望它會奏效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.