Skip to content

Instantly share code, notes, and snippets.

@sunzcdev
Created December 21, 2018 02:42
Show Gist options
  • Save sunzcdev/bfd2d6667fa1a0ff2ec26dc2722be8d2 to your computer and use it in GitHub Desktop.
Save sunzcdev/bfd2d6667fa1a0ff2ec26dc2722be8d2 to your computer and use it in GitHub Desktop.
根据行号截取读取文本文件
public static String readStr(String filepath, int startLine) {
File file = new File(filepath);
if (!file.exists()) return "";
startLine = Math.max(startLine, 1);
LineNumberReader reader = null;
StringBuilder sb = new StringBuilder();
String line;
try {
reader = new LineNumberReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
if (reader.getLineNumber() >= startLine) {
if (reader.getLineNumber() > startLine) {
sb.append("\n");
}
sb.append(line);
}
}
return sb.toString();
} catch (IOException e) {
MyLog.e(TAG, "写文件失败:" + filepath, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment