/**
* 插入文件第一行(推荐)
*
* @param content 要插入的内容
* @throws IOException
*/
public static void insertAtBeginning(String filePath, String content) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
boolean newFile = file.createNewFile();
}
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
byte[] originalContent = new byte[(int) raf.length()];
raf.read(originalContent);
raf.seek(0);
raf.write((content + "\n").getBytes());
raf.write(originalContent);
}
}
/**
* 插入文件第一行 推荐使用 insertAtBeginning
*/
@Deprecated
public static void writeFileToFirstLine(String filePath, String content) {
File file = new File(filePath);
RandomAccessFile randomAccessFile = null;
try {
// 读取原始文件内容
byte[] originalContent = new byte[(int) file.length()];
randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.readFully(originalContent);
// 将文件指针移到开头
randomAccessFile.seek(0);
// 写入新内容
randomAccessFile.write(content.getBytes());
// 写入原始内容
randomAccessFile.write(originalContent);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文本默认写入第一行 插入文本信息到文件第一行
原创
©著作权归作者所有:来自51CTO博客作者痛而不觉的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:org.gradle.api.GradleException: The current Gradle version 5.4.1 is not compatible with the Kotlin G
下一篇:java.lang.AssertionError: annotationType(): unrecognized 属性名称 MODULE #563
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章