public String getFileContent(String fileName, int fromLine, int endLine) {
File file = new File(fileName);
// int total = Integer.parseInt(UnixCommand.WCCommand(file));
int total = 10;
if (endLine == 0) {
return null;
}
if (fromLine == 0) {
fromLine = 1;
}
if (fromLine > 0) {
if (endLine > 0) {
if (fromLine > endLine) {
return null;
}
} else {
endLine = total + endLine + 1;
}
} else {
if (endLine > 0) {
return null;
} else {
int temp = fromLine - endLine;
fromLine = total + endLine + 1;
endLine = fromLine + temp;
}
}
StringBuilder content = new StringBuilder();
LineNumberReader reader = null;
FileReader in = null;
try {
in = new FileReader(file);
reader = new LineNumberReader(in);
while (true) {
String s = reader.readLine();
if (s == null)
break;
int i = reader.getLineNumber();
if (i >= fromLine && i <= endLine) {
content.append(s);
content.append("\r");
}
if (i > endLine) {
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content.toString();
}
Java 按行读取文件
最新推荐文章于 2023-02-23 09:47:53 发布