如何在Java中打开txt文件并读取数字
如何打开.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中打开txt文件并读取数字 的全部内容, 来源链接: utcz.com/qa/426347.html