gpt4 book ai didi

java - 如何从文本文件中读取并存储到java中的数组中

转载 作者:行者123 更新时间:2023-11-30 10:05:53 25 4
gpt4 key购买 nike

我如何从包含大量数字的文本文件中读取并将其存储到一个 int 数组中,最后我将该数组和数组的大小传递给我的其他方法,该方法将在我的应用程序中使用。到目前为止,我的代码从一个文本文件中读取并将其存储到一个 ArrayList 中,而不是一个数组中。谢谢。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.Buffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;

public class Test {

static int i =0;
public static void main(String args[]) throws URISyntaxException {
try {
URL path = ClassLoader.getSystemResource("input.txt");

if ( path== null) {
System.out.println("File is not avilable!");
}

File myfile= new File(path.toURI());
//BufferedReader reader = new BufferedReader (new FileReader(myfile));
Scanner myscan = new Scanner (myfile);

ArrayList<Integer> input = new ArrayList<Integer>();
while (myscan.hasNextLine()) {

input.add(myscan.nextInt());
}
int size = input.size();
System.out.println(input);
System.out.println("this is the array size: "+ size);
}catch (IOException e) {
System.out.println("Something went wrong in your reading file! ");
}
}

}

最佳答案

由于数组的大小是固定的,因此您应该在创建时知道大小,下面的代码给出了 ArrayIndexOutOfBoundException如果文件中有超过 10 个值

int[] input = new int[10]
int i =0;
while (myscan.hasNextLine()) {

input[i]=myscan.nextInt();
i++;
}

所以更喜欢使用 ArrayList<Integer> , 添加文件中的值,然后将其转换为 int数组

int[] arr = input.stream().mapToInt(Integer::intValue).toArray();

关于java - 如何从文本文件中读取并存储到java中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54995255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com