java读取列文件中有不同数字的txt,并将数据存储在arraylist中

mrwjdhj3  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(414)

大家好,我有一个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();
}
ubby3x7f

ubby3x7f1#

如果只想读取并保存第二列,则可以使用索引1获取第二列中的数据(在你的while循环之后。)

String secondCol = sCurrentLine.split(" ")[1];

如果您在2列中没有值,那么它将抛出一个异常,您应该使用简单的try-catch来处理这个异常。最后将其转换为int并存储在列表中。跟在后面。

listOfInteger.add(Integer.parseInt(secoundCol));

希望它能奏效。

4dc9hkyq

4dc9hkyq2#

你不需要再拆线了。第一次拆分行时,请检查结果数组的长度是否为 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 .

相关问题