本文介绍了如何在Java中打开txt文件并读取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何打开.txt文件并将输入或空格分隔的数字读入数组列表?
How can I open a .txt file and read numbers separated by enters or spaces into an array list?
推荐答案
阅读file,将每一行解析为一个整数并存储到一个列表中:
Read file, parse each line into an integer and store into a list:
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中打开txt文件并读取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!