Java:如何读取文本文件的每一行并将每一行设置为数组元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13227587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:57:51  来源:igfitidea点击:

Java: How do you read each line of a text file and setting each line as an array element?

javaarraysfilebufferedreaderfilereader

提问by bigbass1997

I am trying to read questions that are listed in each line of a text file and then adding each line to an array, so that they can be called individually later on. I'm almost positive it is possible to do in Java but I am unsure how to do it.

我正在尝试阅读文本文件每一行中列出的问题,然后将每一行添加到数组中,以便以后可以单独调用它们。我几乎肯定可以用 Java 来做,但我不确定如何去做。

I did figure out how to read a whole text file and setting it all to a string:

我确实想出了如何读取整个文本文件并将其全部设置为字符串:

    private static String readFile(String pathname) {
    String line = null;
    try {
        BufferedReader reader = new BufferedReader(new FileReader(pathname));
        while((line = reader.readLine()) != null){
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return line;
}

Although it doesnt have much to do with this, as I mentioned this is a file that holds questions. If I get a solution to this problem I will be having another file for all the answers to the questions and I will then do the same thing for that file.

虽然它与此没有太大关系,但正如我所提到的,这是一个包含问题的文件。如果我得到了这个问题的解决方案,我将为所有问题的答案创建另一个文件,然后我将为该文件做同样的事情。

Does anyone know of a not overly complicated way to do this? If it has to be complicated then tell me that. I would like some type of example and not just links to different sites. Im not saying I will only take that though.

有谁知道一种不太复杂的方法来做到这一点?如果它必须复杂,然后告诉我。我想要某种类型的示例,而不仅仅是指向不同站点的链接。我不是说我只会接受。

Thank you for your time!

感谢您的时间!

P.S. I have read other questions on this topic but could not find a suitable answer and/or example for what I am trying to do in Java.

PS我已经阅读了关于这个主题的其他问题,但找不到合适的答案和/或我在Java中尝试做的事情的例子。

回答by Yevgeny Simkin

I would use an ArrayList... like so...

我会使用一个 ArrayList ......就像这样......

ArrayList<String> questions = new ArrayList<String>();


/// in your loop...
while((line = reader.readLine()) != null){
  questions.add(line);
}

By the way, as jlordo points out in the comment, the way you've structured your method, the only way out of your loop is for line to be null, so, by the time you get to your return statement you're returning null. What are you actually trying to return here? If it's the entire file of lines you need to be adding them to a String as you go.

顺便说一句,正如 jlordo 在评论中指出的那样,按照您构建方法的方式,退出循环的唯一方法是让 line 为 null,因此,当您到达 return 语句时,您将返回空值。你到底想回到这里做什么?如果它是整个行文件,您需要随时将它们添加到字符串中。

回答by Subhrajyoti Majumder

Instead of array use ArrayList, which is dynamic and find the concrete code.

而不是使用数组ArrayList,这是动态的并找到具体的代码。

private static List<String> readFile(String pathname) {
    String line = null;
    List<String> list = new ArrayList<String>();
    try {
        BufferedReader reader = new BufferedReader(new FileReader(pathname));
        while((line = reader.readLine()) != null){
            list.add(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}

And for the second file, you should maintain a map<question,answer>means a Map<String,String>.

对于第二个文件,您应该维护一个map<question,answer>方式 a Map<String,String>

回答by Lews Therin

 private static String readFile(String pathname) {
    List<String> lines = new ArrayList<String> ();
    String line = null;
    try {
        BufferedReader reader = new BufferedReader(new FileReader(pathname));
        while((line = reader.readLine()) != null){
            lines.add(line) ;
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Use an ArrayList<String>like I did, it grows dynamically. Declare it as a field, I just used a local variable in this example. You can iterate through it later like so:

ArrayList<String>像我一样使用它,它会动态增长。将它声明为一个字段,我在这个例子中只使用了一个局部变量。您可以稍后像这样迭代它:

 for(String line : lines)
   {
      System.out.println(line) ;
    }

回答by futureelite7

Can't you just make a string arraylist and add each line read using readLine() into it? Then you can convert the arraylist into a plain array.

您不能只制作一个字符串数组列表并将使用 readLine() 读取的每一行添加到其中吗?然后,您可以将 arraylist 转换为普通数组。

listArray.toArray(strArray);

回答by u290629

Use Guava Files:

使用番石榴文件

One line code:

一行代码:

System.out.println(Files.readLines(new File("C:\sample.txt"), Charsets.UTF_8));

回答by shakhawat

This is really simple and concise in java 8:

这在 java 8 中非常简单和简洁:

List<String> fileLines = Files.lines(Paths.get("/file/path/")).collect(Collectors.toList());