一、思路
使用 Java 随机访问流 RandomAccessFlie, 从文件末尾追字符判断是否为空白符,找到最后一个非空白符后,计算偏移截断后面的内容即可。
这里判断是否为空白符使用了 org.apache.commons.lang3.StringUtils 工具包
二、代码
Talk is cheap, show me the code. 不解释了,直接看代码吧!
/**
* 去除文件末尾空白内容
* create by kexi on 2021/3/23
* @param file
*/
public static void stripTrailingWhitespace(java.io.File file) throws IOException {
if (!file.exists()) { // 如果文件不存在
return;
}
if (!file.isFile()) { // 如果不是文件类型
return;
}
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
// 每次读取一个字节
int det = 1;
byte[] buff = new byte[det];
// 移动到文件末尾
long offset = raf.length() - 1;
while (true) {
if (offset < 0) break;
raf.seek(offset); // 设置读指针位置
raf.read(buff); // 读取数据
if(StringUtils.isBlank(new String(buff))) { // 如果末尾是空白符
offset -= det;
} else {
break;
}
}
// 截断文件内容
raf.setLength(offset + 1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (raf != null) {
raf.close();
}
}
}
三、测试
// 测试类
public class TestMain {
public static void main(String[] args) {
File file = new File("testFile.txt");
try {
if (!file.exists()) {
file.createNewFile();
}
MyFileUtils.stripTrailingWhitespace(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行前:
运行结果: