Java:如何读取文本文件的每一行并将每一行设置为数组元素? [英] Java: How do you read each line of a text file and setting each line as an array element?

查看:98
本文介绍了Java:如何读取文本文件的每一行并将每一行设置为数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

感谢您的宝贵时间!

附言我已经阅读了有关此主题的其他问题,但找不到合适的答案和/或示例来说明我在 Java 中尝试做的事情.

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.

推荐答案

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

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

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


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

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

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.

这篇关于Java:如何读取文本文件的每一行并将每一行设置为数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆