如何用java在一个文件中合并超过5个txt文件?

rslzwgfq  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(386)

我想在一个txt文件中保存多个txt文件并删除以前的文件。我可以用什么方法?我自己写的代码:

public static void mergeFile() throws IOException {
        long unixTime = System.currentTimeMillis() / 1000L;
        final String sysName = String.valueOf(unixTime);
        File directory = new File("src/");
        FileWriter myWriter = new FileWriter("src/"+sysName+".txt",true);

        File[] files = directory.listFiles();
        for(File file : files) {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String aLine;
            String fileName = file.toString();
            int split = fileName.indexOf(".");
            long fName = Long.parseLong(fileName.substring(5, split)) ;
            if (fName < unixTime) {
                while ((aLine = in.readLine()) != null) {
                    myWriter.write(aLine);
                    myWriter.write("\n");
                }
                in.close();
                file.delete();
            }
        }
    }
gg58donl

gg58donl1#

我重写了上面的代码如下,它工作正常。

public static void mergeFile() throws IOException {
   long unixTime = System.currentTimeMillis() / 1000L;
   final String sysName = String.valueOf(unixTime);
   File directory = new File("src/raw/");
   File[] files = directory.listFiles();
   FileWriter myWriter = new FileWriter("src/ok/"+sysName+".txt");
   for(File file : files) {
      String aLine;
      String fileName = file.toString();
      int split  = fileName.indexOf(".");
      long fName = Long.parseLong(fileName.substring(15, split)) ;
      if (fName <= unixTime) {
         FileInputStream fis = new FileInputStream(file);
         BufferedReader in = new BufferedReader(new InputStreamReader(fis));
         while ((aLine = in.readLine()) != null) {
              myWriter.write(aLine);
              myWriter.write("\n");
            }
            in.close();
         }
         Files.move(Paths.get("src/raw/"+fName+".txt"),
                    Paths.get("src/old/"+fName+".txt"));
      }
      myWriter.close();
      Query.insertSyslog("src/ok/"+sysName+".txt");
}

相关问题