【问题标题】:How to open a txt file and read numbers in Java如何在 Java 中打开 txt 文件并读取数字
【发布时间】:2011-04-17 21:22:04
【问题描述】:

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

【问题讨论】:

    标签: java


    【解决方案1】:
       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 块中关闭输入流。
    • 请不要使用 DataInputStream 读取文本。不幸的是,像这样的示例会一次又一次地被复制,因此您可以将其从示例中删除。 vanillajava.blogspot.co.uk/2012/08/…
    【解决方案2】:

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

    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),因为无论如何你都想要一个对象(整数)。
    • 为什么我们不能将 reader.close(); 移动到 while 循环之后的行并避免整个 finally 块和其他 try-catchfinally 包含 ?
    • @m-d 见Java Tutorial。您应该关闭 finally 中的资源,以确保即使在 try 块内发生异常,它们也始终处于关闭状态。这可以防止资源泄漏。
    • @dogbane:好的,明白了。谢谢。
    • 文件是否打开资源密集型任务?
    【解决方案3】:

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

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

    扫描器使用分隔符模式将其输入分解为标记,默认情况下匹配空格。虽然默认分隔符是空格,但它成功找到了所有由换行符分隔的整数。

    【讨论】:

      【解决方案4】:

      好消息在 Java 8 中我们可以一行完成:

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

      【讨论】:

        【解决方案5】:
        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);
        

        【讨论】:

        • 我喜欢你的回答!它只打印整数并跳过空格、换行符和其他非整数字符的方式
        【解决方案6】:
        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

        另外,我使用数组来简化它......您可以直接将整数输入转换为字符串并将其发送到文件。 input-convert-Write-Process...就这么简单。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-27
          • 1970-01-01
          • 1970-01-01
          • 2021-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多