[英]java: how to use bufferedreader to read specific line
假設我有一個名為的文本文件:data.txt(包含2000行)
如何讀取給定的特定行:500-1500然后1500-2000並顯示特定行的輸出?
此代碼將讀取整個文件(2000行)
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();
}
如何修改上面的代碼以讀取特定的行?
我建議使用java.io.LineNumberReader。 它擴展了BufferedReader,你可以使用它的LineNumberReader.getLineNumber();
獲取當前行號
您還可以使用Java 7 java.nio.file.Files.readAllLines
返回List<String>
如果它更適合您)
注意:
1)在StringBuffer上使用StringBuilder,StringBuffer只是一個遺留類
2) contents.append(System.getProperty("line.separator"))
看起來不太好使用contents.append(File.separator)
代替
3)捕獲異常似乎無關緊要,我還建議將代碼更改為
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();
}
}
現在代碼看起來更干凈了。 如果您使用Java 7,請使用try-with-resources
try (BufferedReader rdr = new BufferedReader(new FileReader("aFile"))) {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
}
所以最后你的代碼看起來像
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() };
}
}
請注意,它返回2個字符串500-1499和1500-2000
更簡潔的解決方案是在apache commons中使用FileUtils。 http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html示例代碼段:
String line = FileUtils.readLines(aFile).get(lineNumber);
更好的方法是使用BufferedReader。 如果您想閱讀第32行,例如:
for(int x = 0; x < 32; x++){
buf.readLine();
}
lineThreeTwo = buf.readLine();
現在在String lineThreeTwo中你存儲了第32行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.