【问题标题】:Java reading a file into an ArrayList?Java将文件读入ArrayList?
【发布时间】:2011-07-17 15:40:22
【问题描述】:

如何在 Java 中将文件内容读入ArrayList<String>

以下是文件内容:

cat
house
dog
.
.
.

只需将每个单词读入ArrayList

【问题讨论】:

    标签: java


    【解决方案1】:

    这段 Java 代码读入每个单词并将其放入 ArrayList:

    Scanner s = new Scanner(new File("filepath"));
    ArrayList<String> list = new ArrayList<String>();
    while (s.hasNext()){
        list.add(s.next());
    }
    s.close();
    

    如果您想逐行而不是逐字阅读,请使用s.hasNextLine()s.nextLine()

    【讨论】:

    • 哦,很好,ScannerBufferedReader 更短,并且没有例外需要处理。我想我已经习惯了在 Java 5 之前使用 BufferedReaderScanner 不存在,尽管我已经使用 Java 5 和 6 很多年了。 Commons IO 库当然会提供最短的答案(如果其他人提到的),所以我现在通常使用它。
    • 您不需要为扫描仪指定分隔符,因为默认分隔符与空格匹配吗?即 new Scanner(new File("filepath")).useDelimiter("\n");
    • @Hedley from java7 on new Scanner(new File("filepath")).useDelimiter(System.lineSeparator()) 因为每个操作系统可能不同
    【解决方案2】:

    你可以使用:

    List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
    

    来源:Java API 7.0

    【讨论】:

    • 我会在这里使用特定的字符集,而不是依赖当前平台的字符集。
    • 你也可以用Paths.get("input.txt")代替new File("input.txt").toPath(0
    【解决方案3】:

    commons-io 的单线:

    List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
    

    guava:

    List<String> lines = 
         Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
    

    【讨论】:

    • 为什么不用Charsets.UTF_8 而不是forName
    【解决方案4】:

    我发现的最简单的形式是......

    List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
    

    【讨论】:

      【解决方案5】:

      Java 8 中,您可以使用流和Files.lines

      List<String> list = null;
      try (Stream<String> lines = Files.lines(myPathToTheFile))) {
          list = lines.collect(Collectors.toList());
      } catch (IOException e) {
          LOGGER.error("Failed to load file.", e);
      }
      

      或者作为一个函数,包括从文件系统加载文件:

      private List<String> loadFile() {
          List<String> list = null;
          URI uri = null;
      
          try {
              uri = ClassLoader.getSystemResource("example.txt").toURI();
          } catch (URISyntaxException e) {
              LOGGER.error("Failed to load file.", e);
          }
      
          try (Stream<String> lines = Files.lines(Paths.get(uri))) {
              list = lines.collect(Collectors.toList());
          } catch (IOException e) {
              LOGGER.error("Failed to load file.", e);
          }
          return list;
      }
      

      【讨论】:

      • List&lt;String&gt; lines = Files.lines(Paths.get("./input.txt")).collect(Collectors.toList());
      【解决方案6】:
      List<String> words = new ArrayList<String>();
      BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
      String line;
      while ((line = reader.readLine()) != null) {
          words.add(line);
      }
      reader.close();
      

      【讨论】:

      • 为什么我用“line.size()”找不到arraylist的大小?
      【解决方案7】:

      例如,您可以通过这种方式执行此操作(包含异常处理的完整代码):

      BufferedReader in = null;
      List<String> myList = new ArrayList<String>();
      try {   
          in = new BufferedReader(new FileReader("myfile.txt"));
          String str;
          while ((str = in.readLine()) != null) {
              myList.add(str);
          }
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          if (in != null) {
              in.close();
          }
      }
      

      【讨论】:

      • 在 Java 7+ 中,您可以使用 try-with-resources
      【解决方案8】:
      //CS124 HW6 Wikipedia Relation Extraction
      //Alan Joyce (ajoyce)
      public List<String> addWives(String fileName) {
          List<String> wives = new ArrayList<String>();
          try {
              BufferedReader input = new BufferedReader(new FileReader(fileName));
              // for each line
              for(String line = input.readLine(); line != null; line = input.readLine()) {
                  wives.add(line);
              }
              input.close();
          } catch(IOException e) {
              e.printStackTrace();
              System.exit(1);
              return null;
          }
          return wives;
      }
      

      【讨论】:

        【解决方案9】:

        这是一个对我来说效果很好的解决方案:

        List<String> lines = Arrays.asList(
            new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
        );
        

        如果你不想要空行,你也可以这样做:

        List<String> lines = Arrays.asList(
            new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
        );
        

        【讨论】:

          【解决方案10】:

          分享一些分析信息。通过一个简单的测试,读取大约 1180 行值需要多长时间。

          如果您需要非常快速地读取数据,请使用旧的 BufferedReader FileReader 示例。我花了~8ms

          扫描仪要慢得多。花了我大约 138 毫秒

          漂亮的 Java 8 Files.lines(...) 是最慢的版本。花了我大约 388 毫秒。

          【讨论】:

            【解决方案11】:

            这是一个完整的程序示例:

            import java.io.File;
            import java.io.FileNotFoundException;
            import java.util.ArrayList;
            import java.util.Scanner;
            
            public class X {
                public static void main(String[] args) {
                File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
                    try{
                        ArrayList<String> lines = get_arraylist_from_file(f);
                        for(int x = 0; x < lines.size(); x++){
                            System.out.println(lines.get(x));
                        }
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
                    System.out.println("done");
            
                }
                public static ArrayList<String> get_arraylist_from_file(File f) 
                    throws FileNotFoundException {
                    Scanner s;
                    ArrayList<String> list = new ArrayList<String>();
                    s = new Scanner(f);
                    while (s.hasNext()) {
                        list.add(s.next());
                    }
                    s.close();
                    return list;
                }
            }
            

            【讨论】:

              【解决方案12】:
                  Scanner scr = new Scanner(new File(filePathInString));
              /*Above line for scanning data from file*/
              
                  enter code here
              
              ArrayList<DataType> list = new ArrayList<DateType>();
              /*this is a object of arraylist which in data will store after scan*/
              
              while (scr.hasNext()){
              

              list.add(scr.next()); } /*上面的代码负责通过add函数在arraylist中添加数据*/

              【讨论】:

                【解决方案13】:

                添加此代码以对文本文件中的数据进行排序。 Collections.sort(list);

                【讨论】:

                • 一般来说,答案如果包含对代码用途的解释会更有用。
                猜你喜欢
                • 2012-04-18
                • 1970-01-01
                • 2016-07-26
                • 2021-03-03
                • 2015-04-25
                • 1970-01-01
                • 2015-05-04
                • 1970-01-01
                相关资源
                最近更新 更多