如何在Java中打开一个txt文件并读取其中的数字

40

我该如何打开一个 .txt 文件,并将以换行符或空格分隔的数字读入到一个数组列表中?

6个回答

63

读取文件,将每一行解析为整数并存入列表:

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);

这很好,但我会使用Integer.valueOf(String),因为你无论如何都想要一个对象(Integer)。 - Mark Peters
为什么我们不能将 reader.close(); 移动到 while 循环后面的那一行,从而避免整个 finally 块以及 finally 包含的其他 try-catch 块? - M-D
2
@m-d 请查看Java教程。您应该在finally中关闭资源,以确保即使在try块内发生异常,它们也始终关闭。这可以防止资源泄漏。 - dogbane
打开文件是一项资源密集型任务吗? - Rishabh Dhiman
使用“try-with-resources”运行此代码也是一个额外的好处:https://dev59.com/TXM_5IYBdhLWcg3waSb9#1388772 - cjnash

23

下面是一个更简短的替代方案:

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将输入拆分为令牌,其中默认情况下匹配空格。虽然默认分隔符是空格,但它可以成功地找到由换行符分隔的所有整数。


11

好消息是在Java 8中我们可以用一行代码实现:

List<Integer> ints = Files.lines(Paths.get(fileName))
                          .map(Integer::parseInt)
                          .collect(Collectors.toList());

3
   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 块中关闭输入流。 - dogbane
请勿使用DataInputStream读取文本。不幸的是,像这样的示例一遍又一遍地被复制,所以你可以从你的示例中删除它。http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html - Peter Lawrey

3
File 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);

我喜欢你的回答!它只打印整数并跳过空格、换行和其他非整数字符的方式。 - Hashmatullah Noorzai

0
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

此外,我使用了数组使其更简单... 您可以直接输入整数并将其转换为字符串,然后将其发送到文件。 输入-转换-写入-处理... 就是这么简单。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接