我该如何打开一个 .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);
下面是一个更简短的替代方案:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
使用分隔符模式将Scanner将输入拆分为令牌,其中默认情况下匹配空格。虽然默认分隔符是空格,但它可以成功地找到由换行符分隔的所有整数。
好消息是在Java 8中我们可以用一行代码实现:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
System.out.println (strLine);
您可以拥有
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
finally
块中关闭输入流。 - dogbaneFile file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
输出: 成功 26
此外,我使用了数组使其更简单... 您可以直接输入整数并将其转换为字符串,然后将其发送到文件。 输入-转换-写入-处理... 就是这么简单。
Integer.valueOf(String)
,因为你无论如何都想要一个对象(Integer)。 - Mark Petersfinally
中关闭资源,以确保即使在try
块内发生异常,它们也始终关闭。这可以防止资源泄漏。 - dogbane