如何使用Java按顺序连接顺序文件?

如何使用Java按顺序连接顺序文件?,java,file-io,concatenation,Java,File Io,Concatenation,我有一个目录,其中包含按顺序编号的日志文件和一些用于分析的Excel电子表格。日志文件始终从零开始按顺序编号,但编号可能会有所不同。我正在尝试将日志文件按创建顺序连接到一个文本文件中,该文本文件将连接所有日志文件 例如,对于日志文件foo0.log、foo1.log、foo2.log,将通过在foo0之后追加foo1,在foo1之后追加foo2,输出到concatenatedfoo.log 我需要对给定目录中扩展名为*.log的所有文件进行计数,使用该计数驱动一个for循环,该循环还生成用于连接

我有一个目录,其中包含按顺序编号的日志文件和一些用于分析的Excel电子表格。日志文件始终从零开始按顺序编号,但编号可能会有所不同。我正在尝试将日志文件按创建顺序连接到一个文本文件中,该文本文件将连接所有日志文件

例如,对于日志文件foo0.log、foo1.log、foo2.log,将通过在foo0之后追加foo1,在foo1之后追加foo2,输出到concatenatedfoo.log

我需要对给定目录中扩展名为*.log的所有文件进行计数,使用该计数驱动一个for循环,该循环还生成用于连接的文件名。我很难找到一种使用过滤器计算文件数的方法……文件操作中的Java Turtorials似乎都不适合这种情况,但我确信我遗漏了一些东西。这种方法有意义吗?还是有更简单的方法

int numDocs = [number of *.log docs in directory];
 //
for (int i = 0; i <= numberOfFiles; i++) {
     fileNumber = Integer.toString(i);
     try
     {
          FileInputStream inputStream = new FileInputStream("\\\\Path\\to\\file\\foo" + fileNumber + ".log");
          BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
          try
          {
               BufferedWriter metadataOutputData = new BufferedWriter(new FileWriter("\\\\Path\\to\\file\\fooconcat.log").append());
               metadataOutputData.close();
          }
           //
          catch (IOException e)  // catch IO exception writing final output
          {
               System.err.println("Exception: ");
               System.out.println("Exception: "+ e.getMessage().getClass().getName());
               e.printStackTrace();
          }
     catch (Exception e)    // catch IO exception reading input file
     {
          System.err.println("Exception: ");
          System.out.println("Exception: "+ e.getMessage().getClass().getName());
          e.printStackTrace();
     }
}
int numDocs=[目录中的*.log文档数];
//
对于(inti=0;ii)

  • 打开输出文件一次。只需使用PrintWriter
  • 在一个循环中。。。
    • 为每个可能的文件创建一个文件
    • 如果它不存在,打破循环
    • 使用BufferedReader
      • 使用readLine()读取文件的行
      • 将每一行写入输出文件

您应该可以使用大约12行代码来完成此操作。我会将IOExceptions传递给调用者。

通过将日志文件夹作为
文件
对象,您可以这样编码

for (File logFile : logFolder.listFiles()){
    if (logFile.getAbsolutePath().endsWith(".log")){
        numDocs++;
    }
}
查找日志文件的数量。

如何

public static void main(String[] args){

    final int BUFFERSIZE = 1024 << 8;
    File baseDir = new File("C:\\path\\logs\\");

    // Get the simple names of the files ("foo.log" not "/path/logs/foo.log")
    String[] fileNames = baseDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".log");
        }
    });

    // Sort the names
    Arrays.sort(fileNames);

    // Create the output file
    File output = new File(baseDir.getAbsolutePath() + File.separatorChar + "MERGED.log");
    try{
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(output), BUFFERSIZE);
        byte[] bytes = new byte[BUFFERSIZE];
        int bytesRead;
        final byte[] newLine = "\n".getBytes(); // use to separate contents

        for(String s : fileNames){
            // get the full path to read from
            String fullName = baseDir.getAbsolutePath() + File.separatorChar + s;
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(fullName),BUFFERSIZE);
            while((bytesRead = in.read(bytes,0,bytes.length)) != -1){
                out.write(bytes, 0, bytesRead);
            }
            // close input file and ignore any issue with closing it
            try{in.close();}catch(IOException e){}
            out.write(newLine); // seperation
        }

        out.close();
    }catch(Exception e){
        throw new RuntimeException(e);
    }
}
publicstaticvoidmain(字符串[]args){

final int BUFFERSIZE=1024以下是一些代码

File dir = new File("C:/My Documents/logs");
File outputFile = new File("C:/My Documents/concatenated.log");
查找“.log”文件:

将它们按适当的顺序排序:

Arrays.sort(files, new Comparator<File>() {

    @Override
    public int compare(File file1, File file2) {
        return numberOf(file1).compareTo(numberOf(file2));
    }

    private Integer numberOf(File file) {
        return Integer.parseInt(file.getName().replaceAll("[^0-9]", ""));
    }
});
可以用于连接
文件输入流
。 查看可以使用的所有日志文件。 它将为您提供包含文件的未排序数组。若要按正确顺序对文件进行排序,请使用
Arrays.sort
。 代码示例:

static File[] logs(String dir) {
    File root = new File(dir);
    return root.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isFile() && pathname.getName().endsWith(".log");
        }
    });
}

static String cat(final File[] files) throws IOException {
    Enumeration<InputStream> e = new Enumeration<InputStream>() {
        int index;

        @Override
        public boolean hasMoreElements() {
            return index < files.length;
        }

        @Override
        public InputStream nextElement() {
            index++;
            try {
                return new FileInputStream(files[index - 1]);
            } catch (FileNotFoundException ex) {
                throw new RuntimeException("File not available!", ex);
            }
        }
    };
    SequenceInputStream input = new SequenceInputStream(e);
    StringBuilder sb = new StringBuilder();
    int c;
    while ((c = input.read()) != -1) {
        sb.append((char) c);
    }
    return sb.toString();
}

public static void main(String[] args) throws IOException {
    String dir = "<path-to-dir-with-logs>";
    File[] logs = logs(dir);
    for (File f : logs) {
        System.out.println(f.getAbsolutePath());
    }
    System.out.println();
    System.out.println(cat(logs));
}
静态文件[]日志(字符串目录){
文件根=新文件(目录);
返回root.listFiles(新文件过滤器(){
@凌驾
公共布尔接受(文件路径名){
返回pathname.isFile()&&pathname.getName().endsWith(“.log”);
}
});
}
静态字符串cat(最终文件[]文件)引发IOException{
枚举e=新枚举(){
整数指数;
@凌驾
公共布尔值hasMoreElements(){
返回索引
打开一个操作系统。然后,对于每个操作系统-打开,循环[read IS/write OS]并依次关闭。最后,您可以在写入所有内容后关闭操作系统。即使打开操作系统进行附加(如上所述),也必须向其写入某些内容(如上所述)。此外,如果适合与所需的启发式方法一起使用,可以使用a,而不是计算然后尝试导出文件名。假设所有日志都来自同一个源,并且不需要编码转换,我建议使用字节流,而不是读写器,因为后者是多余的,而且还可能损坏cont如果您对编码不小心(UTF-8、Cp1252等),请使用ents@aetheria这也会保留原来的换行符。这一个非常好用,只不过我的文件名是
foo0.log
foo10.log
…等等。但是重命名排序或类似的操作应该相对简单。如果你想让它按照你当前的约定排序,只需重新命名在我的行中,“
Arrays.sort(filename);
和@aetheria的答案的
Arrays.sort(files,new Comparator(){…}
部分。这应该可以工作,但我没有测试。我在连接步骤中遇到一些问题…我一直得到“catch without try”或“exception must be be be capture”错误“?我似乎无法将它们添加到正确的位置。对方法
@Override
s不太熟悉,因此我认为我对try/catch对范围的看法有点模糊…?我将通过Java教程对此进行研究,但与此同时,有什么提示吗?我找到了最好的答案。”
byte[] buffer = new byte[8192];

OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        try {
            int charCount;
            while ((charCount = in.read(buffer)) >= 0) {
                out.write(buffer, 0, charCount);
            }
        } finally {
            in.close();
        }
    }
} finally {
    out.flush();
    out.close();
}
static File[] logs(String dir) {
    File root = new File(dir);
    return root.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isFile() && pathname.getName().endsWith(".log");
        }
    });
}

static String cat(final File[] files) throws IOException {
    Enumeration<InputStream> e = new Enumeration<InputStream>() {
        int index;

        @Override
        public boolean hasMoreElements() {
            return index < files.length;
        }

        @Override
        public InputStream nextElement() {
            index++;
            try {
                return new FileInputStream(files[index - 1]);
            } catch (FileNotFoundException ex) {
                throw new RuntimeException("File not available!", ex);
            }
        }
    };
    SequenceInputStream input = new SequenceInputStream(e);
    StringBuilder sb = new StringBuilder();
    int c;
    while ((c = input.read()) != -1) {
        sb.append((char) c);
    }
    return sb.toString();
}

public static void main(String[] args) throws IOException {
    String dir = "<path-to-dir-with-logs>";
    File[] logs = logs(dir);
    for (File f : logs) {
        System.out.println(f.getAbsolutePath());
    }
    System.out.println();
    System.out.println(cat(logs));
}