【问题标题】:Java read certain line from txt fileJava从txt文件中读取某行
【发布时间】:2014-03-20 22:44:42
【问题描述】:

我想从文件中读取第二行文本并将其放入数组中。我已经让它在第一行工作了。

        [ Code removed as requested ]

上面的 while 循环显示了我如何读取文本文件的第一行并将其保存到数组中。我希望只从第二行重复这个过程到不同的数组中。

文件内容:

沙发、扶手椅、电脑桌、茶几、电视柜、靠垫、床、床垫、羽绒被、枕头 599.99,229.99,129.99,40.00,37.00,08.00,145.00,299.99,24.99,09.99

【问题讨论】:

  • Swing 代码与读取文件的问题无关。请删除它。
  • 发布大量不相关的代码或删除相关代码,或滥用试图帮助您的人,您都不会获得帮助。您还忽略了我已经也回答了您的问题,但现在您已经删除了所有代码,无法进一步帮助您。祝你好运。

标签: java file text io


【解决方案1】:

只需摆脱第一个 readLine() 调用,并将 String.split() 调用移入循环。

【讨论】:

  • 那我会用for循环来分隔数组吗?
【解决方案2】:

只需使用 BufferedReader 类读取整个文件,然后操作字符串输出。

类似的东西

public static String readFile(String fileName) throws IOException {
    String toReturn = "";
    BufferedReader br = null;

    try {
        String sCurrentLine;
        br = new BufferedReader(new FileReader("test.txt"));
        while ((sCurrentLine = br.readLine()) != null) {
            toReturn = toReturn+"\n"+sCurrentLine;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return toReturn;
}

会产生一个可以轻松使用的字符串。

【讨论】:

  • 谢谢 :) 认为我可以这样做。
【解决方案3】:
public static void main(String[] args)
{
    String filePath = args[0];
    String[] lineElements = getLine(filePath,2).split(",");
}

public static String getLine(String path,int line)
{
    List<String> cases = new ArrayList<String>();
    try{
        BufferedReader br = new BufferedReader(new FileReader(path));

        String currLine = "";
        while((currLine = br.readLine()) != null){
            cases.add(currLine);
        }
    }catch(IOException ex){
        ex.printStackTrace();
    }

    return cases.get(line - 1);//2nd line
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2016-05-27
    相关资源
    最近更新 更多