【问题标题】:Read in file and store into a dynamically allocated string array读入文件并存储到动态分配的字符串数组中
【发布时间】:2017-11-04 10:55:51
【问题描述】:

这里是初级 Java 程序员。我在互联网上搜索了一段时间,但没有成功。

我需要读入一个文本文件并将每一行存储到一个字符串数组中。但是我不知道文本文件有多大,因此我试图找出一种简单的方法来动态分配字符串数组的大小。我不知道 Java 库中是否已经有一个方便的工具可以使用。我在想也许先计算文件中的总行数,然后分配字符串数组,但我也不知道最好的方法。

感谢您的任何意见!

【问题讨论】:

  • 使用数组列表。要读入整个文件,请使用流。使用缓冲阅读器。文件的读取应该在 while 循环中完成,使用 ReadLine,并循环直到下一个 ReadLine 不为空。然后,您可以确定数组列表的大小,并定义一个该长度的数组,然后将数组列表的内容传输到数组中。

标签: java arrays string file io


【解决方案1】:

如果你只想要 Java8+ 中的工作程序(而不是练习编码和调试):

 String[] ary = java.nio.file.Files.readAllLines(Paths.get(filename)).toArray(new String[0]);
 // substitute the (Path,Charset) overload if your data isn't compatible with UTF8
 // if a List<String> is sufficient for your needs omit the .toArray part

【讨论】:

    【解决方案2】:

    定义一个不需要固定长度的数组列表,因为您可以添加或删除任意数量的元素:

        List<String> fileList = new ArrayList<String>();
        //Declare a file at a set location:
        File file = new File("C:\\Users\\YourPC\\Desktop\\test.txt");
        //Create a buffered reader that reads a file at the location specified:
        try (BufferedReader br = new BufferedReader(new FileReader(file)))
        {
            String line;
            //While there is something left to read, read it:
            while ((line = br.readLine()) != null)
                //Add the line to the array-list:
                fileList.add(line);
        }catch(Exception e){
            //If something goes wrong:
            e.printStackTrace();
        }
    
        //Determine the length of the array-list:
        int listTotal = fileList.size();
        //Define an array of the length of the array-list:
        String[] fileSpan = new String[listTotal];
    
        //Set each element index as its counterpart from the array-list to the array:
        for(int i=0; i<listTotal; i++){
    
            fileSpan[i] = fileList.get(i);
        }
    

    【讨论】:

    • 太好了,感谢您的帮助。这比我自己编写的代码效率高得多!此外,这段代码片段真的可以帮助我入门。谢谢!
    【解决方案3】:

    您可以使用ArrayList 而不必担心大小:

    List<String> fileLines = new ArrayList<String>();
    
    try (BufferedReader br = new BufferedReader(new FileReader(file)))
    {
        String line;
        while ((line = br.readLine()) != null)
            fileLines.add(line);
    }
    

    fileLines 可能会变得非常大,但如果您对此感到满意,那么这是一种简单的入门方式。

    【讨论】:

    • 还要确保文件大小不超过为 jvm 进程分配的堆内存。
    • 太好了,感谢您的帮助。这比我自己写的代码效率高得多!
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 2020-10-12
    • 2012-08-18
    相关资源
    最近更新 更多