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

查看:1079
本文介绍了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.

感谢您的时间!

P.S。我已阅读关于这一主题的其他问题,但找不到我试图用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的评论,你的结构化方法的方式,你的循环的唯一出路指出的是用于线路为空,那么,你的时间找到您的return语句你'重新返回null。什么是你真正想回到这里?如果它是行的整个文件,你需要将它们添加到字符串,当您去。

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天全站免登陆