JAVA将整数从文件读取到两个不同的数组

ssm49v7z  于 2022-10-30  发布在  Java
关注(0)|答案(2)|浏览(130)

我的档桉是这样的

3 5 7 9
2 4 6 5

我想把第一行的值放入arrayA,第二行的值放入arrayB,这就是我现在所拥有的。

while(sc.hasNextLine()) {
            while (sc.hasNextInt()) {
                arrA[i] = sc.nextInt();
                arrB[i] = Integer.parseInt(sc.nextLine());
                i++;
            }
        }
svmlkihl

svmlkihl1#

可能是这样的

String s = sc.readLine();
Integer[] arrA = Arrays.stream(s.split(" ")).map(Integer::parseInt).collect(Collectors.toList()).toArray(new Integer[0]);
zz2j4svz

zz2j4svz2#

public class ReadFileToArray {
public static void main(String[] args) throws IOException {
    Path path = Paths.get("./abc.txt");
    List<List<char[]>> listOfArrays = new ArrayList<>();

    if (Files.exists(path)) {
        List<String> readAllLines = Files.readAllLines(path);
        if (!CollectionUtils.isEmpty(readAllLines)) {
            readAllLines.forEach(line -> {
                if (Objects.nonNull(line)) {
                    listOfArrays.add(Collections.singletonList(line.toCharArray()));
                }
            });
        }
    }

    if (!CollectionUtils.isEmpty(listOfArrays)) {
        listOfArrays.forEach(listOfArray -> listOfArray.forEach(System.out::println));
    }
} }

文件:abc.txt
三五七九
二四六五

输出:

三五七九
二四六五

相关问题