java: how to use bufferedreader to read specific line

后端 未结 3 501
情话喂你
情话喂你 2020-12-16 06:12

Lets say I have a text file called: data.txt (contains 2000 lines)

How do I read given specific line from: 500-1500 and then 1500-2000 and display the output of spec

相关标签:
3条回答
  • 2020-12-16 06:50

    A slightly more cleaner solution would be to use FileUtils in apache commons. http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html Example snippet:

    String line = FileUtils.readLines(aFile).get(lineNumber);
    
    0 讨论(0)
  • 2020-12-16 06:58

    I suggest java.io.LineNumberReader. It extends BufferedReader and you can use its LineNumberReader.getLineNumber(); to get the current line number

    You can also use Java 7 java.nio.file.Files.readAllLines which returns a List<String> if it suits you better

    Note:

    1) favour StringBuilder over StringBuffer, StringBuffer is just a legacy class

    2) contents.append(System.getProperty("line.separator")) does not look nice use contents.append(File.separator) instead

    3) Catching exception seems irrelevant, I would also suggest to change your code as

    public static String getContents(File aFile) throws IOException {
        BufferedReader rdr = new BufferedReader(new FileReader("aFile"));
        try {
            StringBuilder sb = new StringBuilder();
            // read your lines
            return sb.toString();
        } finally {
            rdr.close();
        }
    }
    

    now code looks cleaner in my view. And if you are in Java 7 use try-with-resources

        try (BufferedReader rdr = new BufferedReader(new FileReader("aFile"))) {
            StringBuilder sb = new StringBuilder();
            // read your lines
            return sb.toString();
        }
    

    so finally your code could look like

    public static String[] getContents(File aFile) throws IOException {
        try (LineNumberReader rdr = new LineNumberReader(new FileReader(aFile))) {
            StringBuilder sb1 = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            for (String line = null; (line = rdr.readLine()) != null;) {
                if (rdr.getLineNumber() >= 1500) {
                    sb2.append(line).append(File.pathSeparatorChar);
                } else if (rdr.getLineNumber() > 500) {
                    sb1.append(line).append(File.pathSeparatorChar);
                }
            }
            return new String[] { sb1.toString(), sb2.toString() };
        }
    }
    

    Note that it returns 2 strings 500-1499 and 1500-2000

    0 讨论(0)
  • 2020-12-16 07:05

    The better way is to use BufferedReader. If you want to read line 32 for example:

    for(int x = 0; x < 32; x++){
        buf.readLine();
    }
    lineThreeTwo = buf.readLine();
    

    Now in String lineThreeTwo you have stored line 32.

    0 讨论(0)
提交回复
热议问题