小编上次文件丢失电脑硬盘分区删了格式化了文件如何恢复,硬盘数据恢复后,找回的文件最后一行有NUL字符,想着怎么去掉,因为文件很多,就写了个java处理程序,处理掉NUL部分主要参考java删除文本文件最后一行为NUL的字符,这里介绍的是删除最后一样,但是考虑到我的文件最后一样有正确文本和NUL掺杂的情况,于是对代码做了一些修改。
有这样的:
也有这样的
好在NUL字符都在文件末尾,恢复后这些文件都变成了ANSI编码,小编当时写的时候是UTF-8编码
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
public class DelNul {
// static String src = "E:\\abc\\";
static String src = "E:\\abc\\";// 路径最后必须带/
static long maxDateTime = dateToStamp("2022-02-21 00:00:00");
public static void main(String args[]) throws Exception {
processDirMain();
//processFile();
}
public static void processFile() {
File strFile = new File("E:\\abc\\consumer-rules.pro");
// DateUtils.stampToDate(strFile.lastModified());
if (strFile.exists()
&& strFile.lastModified() < maxDateTime
) {
delNulEndFile(strFile);
} else {
System.out.println("不符合");
}
}
public static boolean isNeedProcessDir(File strFile) {
if(strFile == null || !strFile.exists() || !strFile.isDirectory() ) {
return false;
}
String fileNme = strFile.getName();
if (
strFile.isHidden()
//||strFile.equals("out")
//||strFile.equals("build")
//||strFile.startsWith(".")
|| fileNme.equals(".gradle")
|| fileNme.equals(".idea")
|| fileNme.equals("build")
//||strFile.equals(".settings")
|| fileNme.equals(".metadata")
) {
System.err.println(strFile.getAbsolutePath()+"不处理");
return false;
} else {
return true;
}
}
public static boolean isNeedProcessFile(File strFile) {
if (strFile == null || !strFile.exists() || !strFile.isFile()) {
return false;
}
String fileNme = strFile.getName();
if (strFile.lastModified() >= maxDateTime
|| strFile.isHidden()
|| fileNme.endsWith(".rar")
|| fileNme.endsWith(".zip")
|| fileNme.endsWith(".7z")
|| fileNme.endsWith(".gz")
|| fileNme.endsWith(".rpm")
|| fileNme.endsWith(".exe")
|| fileNme.endsWith(".doc")
|| fileNme.endsWith(".jar")
|| fileNme.endsWith(".aar")
|| fileNme.endsWith(".so")) {
System.err.println(strFile.getAbsolutePath() + "不处理");
return false;
} else {
return true;
}
}
public static void processDirMain() throws IOException {
File filesrc = new File(src);
if (!filesrc.exists()) {
System.out.println("目标文件不存在!");
return;
}
File[] file = filesrc.listFiles();
if (file == null) {
System.out.println("目录为空");
return;
}
System.out.println("******开始处理******");
java.util.Date now = new java.util.Date();
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
String hehe = dateFormat.format(now);
System.out.println(hehe);
for (int i = 0; i < file.length; i++) {
System.out.println(file[i].getName() + " 开始处理!");
if (isNeedProcessFile(file[i])) {
delNulEndFile(file[i]);
System.out.println(file[i].getName() + " 文件处理完成!" + "这是第" + i + "个,共" + file.length);
} // file[i].getPath().indexOf("/.") == -1
else if (isNeedProcessDir(file[i])) {
System.out.println(file[i].getName() + " 目录开始处理!");
String sourceDir = src + File.separator + file[i].getName();
processDirectiory(sourceDir);
System.out.println(file[i].getName() + " 目录处理完成!" + "这是第" + i + "个,共" + file.length);
}
}
System.out.println("############全部处理结束!############");
java.util.Date now2 = new java.util.Date();
java.text.SimpleDateFormat dateFormat2 = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
String hehe2 = dateFormat2.format(now2);
System.out.println(hehe2);
}
public static void processDirectiory(String sourceDir) throws IOException {
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (isNeedProcessFile(file[i])) {
File sourceFile = file[i];
delNulEndFile(sourceFile);
} else if (isNeedProcessDir(file[i])) {
String dir1 = sourceDir + File.separator + file[i].getName();
System.out.println(dir1 + "开始处理");
processDirectiory(dir1);
}
}
}
/**
* https://www.cnblogs.com/baby123/p/12706280.html
*
* @param fileName
* @throws Exception
*/
public static void delNulEndFile(File srcfile) {
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(srcfile == null || !srcfile.exists()) {
System.err.println("delNulEndFile error");
return;
}
System.out.println(srcfile.getAbsolutePath());
try {
RandomAccessFile file = new RandomAccessFile(srcfile, "rw");
long len = file.length();
if (len == 0) {
System.err.println("len is 0,not process");
file.close();
return;
}
long start = file.getFilePointer();
long nextend = start + len - 1;
int i = -1;
// 移动指针
file.seek(nextend);
byte[] buf = new byte[1];
boolean isDelete = false;
while (nextend > start) {
i = file.read(buf, 0, 1);
// System.out.println(buf[0]);
if (buf[0] != 0) {
isDelete = true;
}
// 删除最后的NUL字符
if (isDelete) {
file.setLength(nextend + 1);
System.out.println(srcfile.getAbsolutePath()+"...");
break;
}
nextend--;
//System.out.println(nextend);
file.seek(nextend);
}
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.err.println(e);
e.printStackTrace();
}
}
});
}
/**
* https://www.cnblogs.com/baby123/p/12706280.html
*
* @param fileName
* @throws Exception
*/
public static void delNulAtLastLine(String fileName) throws Exception {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
long len = file.length();
long start = file.getFilePointer();
long nextend = start + len - 1;
int i = -1;
// 移动指针
file.seek(nextend);
byte[] buf = new byte[1];
boolean isDelete = true;
while (nextend > start) {
i = file.read(buf, 0, 1);
System.out.println(buf[0]);
if (buf[0] == 0) {
isDelete = true;
}
if (buf[0] == '\r') {
// 删除最后一行
if (isDelete) {
file.setLength(nextend - start);
}
break;
}
nextend--;
file.seek(nextend);
}
file.close();
}
// 将时间转换为时间戳
public static long dateToStamp(String s) {
String res = "";
// 设置时间格式,将该时间格式的时间转换为时间戳
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date;
try {
date = simpleDateFormat.parse(s);
long time = date.getTime();
//res = String.valueOf(time);
System.out.println(time);
return time;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return System.currentTimeMillis();
}
}
对于大量文件的处理还是很耗时的,博主只是在处理的时候用了多线程,文件夹遍历的时候并没有使用多线程,后续有时间看看能不能优化,尽量缩短处理时间
参考
java删除文本文件最后一行为NUL的字符
Notepad++中如何替换掉NUL不可见字符【原创】