Created
December 21, 2018 02:42
-
-
Save sunzcdev/bfd2d6667fa1a0ff2ec26dc2722be8d2 to your computer and use it in GitHub Desktop.
根据行号截取读取文本文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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