读取文件内容(从最后一行开始)
/**
* @param filename 目标文件
* @param charset 目标文件的编码格式
*/
public static String read(String filename, String charset, Integer last) {
StringBuilder stringBuilder = new StringBuilder();
int d = 0;
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(filename, "r");
long len = rf.length();
long start = rf.getFilePointer();
long nextend = start + len - 1;
String line;
rf.seek(nextend);
int c;
while (nextend > start) {
c = rf.read();
if (c == '\n' || c == '\r') {
line = rf.readLine();
if (d++ == last) {
break;
}
if (line == null) {
line = "";
}
stringBuilder.append(new String(line .getBytes(StandardCharsets.ISO_8859_1), charset)).append("\n");
nextend--;
}
nextend--;
rf.seek(nextend);
if (nextend == 0) {
if (d++ == last) {
break;
}
stringBuilder.append(new String(rf.readLine() .getBytes(StandardCharsets.ISO_8859_1), charset)).append("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (rf != null)
rf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
写入指定位置
//传入两个参数,content内容,title文件名
public static void writeTxt(String content) {
try {
//创建文件路径
File writename1 = new File("D:\\test\\1.txt");
//判断是否存在
if (!writename1.exists()) {
//不存在就创建
writename1.createNewFile();
}
//创建写入文件方式,true为追加写入,原内容不覆盖
FileWriter fw = new FileWriter(writename1, true);
//追加写入
fw.append(content + "\n");
//刷新
fw.flush();
//关闭资源
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
执行
public static void main(String[] args) {
String read = read("D:\\test\\abc.txt", "UTF-8", 10000);
writeTxt(read);
}
结果
- 原始文件

- 输出文件
