【问题标题】:How to copy a txt line into an ArrayList in java?java - 如何将txt行复制到java中的ArrayList中?
【发布时间】:2016-03-29 19:24:57
【问题描述】:

我正在尝试读取文本并将其中的每一行保存到 ArrayList 的新元素中。无论如何要继续阅读和添加 ArrayList 直到它到达文件末尾或当阅读器没有找到任何其他要阅读的行时?

此外,最好用什么? Scanner 还是 BufferedReader?

【问题讨论】:

标签: java text arraylist


【解决方案1】:

传统上,您会执行以下操作:

  • 创建ScannerBufferedReader 的实例
  • 设置条件以持续读取文件(使用Scanner,通过scanner.hasNextLine();使用BufferedReader,还有一点工作要做)
  • 从中获取下一行并将其添加到您的列表中。

但是,使用 Java 7 的 NIO 库,您根本不需要这样做。

您可以利用Files#readAllLines 来完成您想要的;无需自己进行任何迭代。您必须提供文件路径和字符集(即Charset.forName("UTF-8");),但它的工作原理基本相同。

Path filePath = Paths.get("/path/to/file/on/system");
List<String> lines = Files.readAllLines(filePath, Charset.forName("UTF-8"));

【讨论】:

    【解决方案2】:

    FWIW,如果你使用的是Java8,你可以使用stream APIs,如下所示

    public static void main(String[] args) throws IOException {
    
        String filename = "test.txt"; // Put your filename
        List fileLines = new ArrayList<>();
    
        // Make sure to add the "throws IOException" to the method  
        Stream<String> fileStream = Files.lines(Paths.get(filename));
        fileStream.forEach(fileLines::add);        
    }
    

    我这里有一个main 方法,只需将它放在你的方法中并添加throws 语句或try-catch

    您也可以将上述内容转换为单行

    ((Stream<String>)Files.lines(Paths.get(filename))).forEach(fileLines::add);
    

    【讨论】:

      【解决方案3】:

      尝试像这样使用BufferedReader

      static List<String> getFileLines(final String path) throws IOException {
      
          final List<String> lines = new ArrayList<>();
      
          try (final BufferedReader br = new BufferedReader(new FileReader(path))) {
              string line = null;
              while((line = br.readLine()) != null) {
                  lines.add(line);
              }
          }
      
          return lines;
      }
      
      • 为结果创建一个空列表。
      • BufferedReader 上使用 try-with-resources 语句来安全地打开和关闭文件
      • 读取行直到BufferedReader 返回null
      • 返回列表

      【讨论】:

        【解决方案4】:

        由于您想从特定文本文件中读取整行,我建议您使用 BufferedReader 类。

        你可以像这样创建一个 BufferedReader 对象:

        BufferedReader br = new BufferedReader(new FileReader(filenName));//fileName is a string
        //that contains the name of the file if its in the same folder or else you must give the relative/absolute path to the file
        

        然后使用 BufferedReader 对象上的 readLine() 函数读取文件的每一行。 您可以尝试以下方法。

            try
            {
                //read each line of the file
                while((line = br.readLine()) != null)//if it reaches the end of the file rd will be null
                {
                  //store the contents of the line into an ArrayList object
                }
            }catch(IOException ex)
            {
                System.out.println("Error");
            }
        

        【讨论】:

          【解决方案5】:

          你可能会使用

          final List<String> lines =
             Files.lines(Paths.get(path)).collect(Collectors.toList());
          

          或带有lines(Path, Charset)的变体。

          【讨论】:

            猜你喜欢
            • 2019-02-28
            • 2019-10-05
            • 1970-01-01
            • 2011-12-07
            • 1970-01-01
            • 1970-01-01
            • 2013-10-04
            • 2020-04-01
            • 1970-01-01
            相关资源
            最近更新 更多