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 specific line?
this code will read whole files (2000 line)
public static String getContents(File aFile) {
StringBuffer contents = new StringBuffer();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
How do I modify above code to read specific line?
The better way is to use BufferedReader. If you want to read line 32 for example:
Now in String lineThreeTwo you have stored line 32.
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:
I suggest java.io.LineNumberReader. It extends BufferedReader and you can use its
LineNumberReader.getLineNumber();
to get the current line numberYou can also use Java 7
java.nio.file.Files.readAllLines
which returns aList<String>
if it suits you betterNote:
1) favour StringBuilder over StringBuffer, StringBuffer is just a legacy class
2)
contents.append(System.getProperty("line.separator"))
does not look nice usecontents.append(File.separator)
instead3) Catching exception seems irrelevant, I would also suggest to change your code as
now code looks cleaner in my view. And if you are in Java 7 use try-with-resources
so finally your code could look like
Note that it returns 2 strings 500-1499 and 1500-2000