gpt4 book ai didi

java - 如何在 Java 中打开 txt 文件并读取数字

转载 作者:IT老高 更新时间:2023-10-28 20:52:52 24 4
gpt4 key购买 nike

如何打开 .txt 文件并将由输入或空格分隔的数字读入数组列表?

最佳答案

读取文件,将每一行解析为一个整数并存储到一个列表中:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
reader = new BufferedReader(new FileReader(file));
String text = null;

while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}

//print out the list
System.out.println(list);

关于java - 如何在 Java 中打开 txt 文件并读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3806062/

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