import java.io.;
import java.util.;
public class Main {
private static final String logName = “j.log”;
private static final String parentPath = “E:\taskId”;
/**
* 读取文件的内容,追加到j.log
*
* @param filePath filePath
* @param out out
/
public static void readTxtFile(String filePath,
BufferedWriter out) throws IOException {
InputStreamReader read = null;
BufferedReader bufferedReader = null;
try {
String encoding = “UTF8”;
File file = new File(filePath);
//判断文件是否存在
if (file.isFile() && file.exists()) {
// 考虑到编码格式
read = new InputStreamReader(
new FileInputStream(file), encoding);
bufferedReader = new BufferedReader(read);
String lineTxt;
while ((lineTxt = bufferedReader.readLine()) != null) {
out.append(lineTxt).append(System.getProperty(“line.separator”));
}
} else {
System.out.println(“找不到指定的文件”);
}
} catch (Exception e) {
System.out.println(“读取文件内容出错”);
e.printStackTrace();
} finally {
bufferedReader.close();
read.close();
}
}
/*
* 写入文件
*
* @param m
/
public static void writeTxtFile(String m) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(“runoob.txt”));
out.append(m);
out.close();
System.out.println(“文件创建成功!”);
} catch (IOException e) {
}
}
/*
* 获取某个目录下所有直接下级文件,不包括目录下的子目录的下的文件,所以不用递归获取
*
* @param path
* @return
*/
public static List getFiles(String path) {
List files = new ArrayList<>();
File file = new File(path);
File[] tempList = file.listFiles();
for (File value : tempList) {
if (value.isFile()) {
files.add(value.getName().toString());
}
}
return files;
}
public static void main(String[] argv) throws IOException {
long t1 = System.currentTimeMillis();
List fileNames = getFiles(parentPath);
fileNames.remove(logName);
fileNames.sort((s1, s2) -> {
int i1 = Integer.parseInt(s1.split("-")[0]);
int i2 = Integer.parseInt(s2.split("-")[0]);
return i1 - i2;
});
BufferedWriter out = new BufferedWriter(new FileWriter(parentPath + File.separator + logName, true));
fileNames
.forEach(fileName -> {
try {
readTxtFile(parentPath + File.separator + fileName, out);
} catch (IOException e) {
e.printStackTrace();
}
});
out.close();
System.out.println((System.currentTimeMillis() - t1) / 1000);
}
}
读取文件排序写文件
最新推荐文章于 2022-04-20 12:43:35 发布