读取文件排序写文件

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);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值