首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一种程序设计任务,如果多个文件名称匹配,则将它们合并为一个文件。FileWriter/BufferedWriter

一种程序设计任务,如果多个文件名称匹配,则将它们合并为一个文件。FileWriter/BufferedWriter
EN

Stack Overflow用户
提问于 2012-08-01 02:10:11
回答 1查看 642关注 0票数 0

好的,所以我要做一项任务:

假设你有如下排序的聊天日志:

代码语言:javascript
复制
System-0/Server-#channel.log
System-0/Server-#channel1.log
System-0/Server-#channel2.log
System-1/Server-#channel.log
System-1/Server-#channel2.log
System-2/Server-#channel3.log

System-0是我的第一个系统,system 1和system 2是其他计算机。如何合并System-0/#channel和System-1/#channel日志文件?我已经知道了如何获取它们,然而,BufferedWriter会随机停止写入(它会忘记文本),并且它只适用于1个文件(所以假设在不同的目录中有2个重复的日志文件,它只会处理不同目录中的第一个重复的日志文件)。

很抱歉我的英语,我不是一个以英语为母语的人,但我希望你能理解我的意思。这是我到目前为止所做的:我也对任何改进都持开放态度。

代码语言:javascript
复制
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class MergeV2 {

private static final Logger log = Logger.getLogger(MergeV2.class.getName());
private static final File ROOT_FOLDER = new File(System.getProperty("user.home") + (System.getProperty("os.name").contains("Windows") ? "/AppData/Roaming/X-Chat 2/xchatlogs" : "/.xchat2/xchatlogs"));
private static final HashMap<String, File[]> files = new HashMap<String, File[]>();
private static final HashMap<File, File[]> filesToWrite = new HashMap<File, File[]>();

public static void main(String... args) {
    if (ROOT_FOLDER.exists()) {
        for (final File f : ROOT_FOLDER.listFiles()) {
            if (f.isDirectory() && f.getName().contains("System")) { //mandatory check
                for (final File sub : f.listFiles()) {
                    String channelName = sub.getName().split("#")[1].replaceAll(".log", "");
                    if (files.containsKey(channelName)) {
                        ArrayList<File> tempFiles = new ArrayList<File>();
                        for (File t : files.get(channelName)) {
                            tempFiles.add(t);
                        }
                        tempFiles.add(sub);
                        File[] array = new File[tempFiles.size()];
                        array = tempFiles.toArray(array);
                        files.put(channelName, array);
                    } else {
                        files.put(channelName, new File[]{sub});
                    }
                }
            }
        }
    } else {
        log.info("No log folder detected.");
    }
    String channel;
    File f, ftemp;
    for (Map.Entry<String, File[]> es : files.entrySet()) {
        channel = "#" + es.getKey();
        f = new File(ROOT_FOLDER.getAbsolutePath() + "/merged-" + channel + ".log");
        ftemp = new File(f.getAbsolutePath() + ".temp");
        if (f.exists()) {
            f.delete();
            ftemp.delete();
        }
        try {
            f.createNewFile();
            ftemp.createNewFile();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        filesToWrite.put(f, es.getValue());
    }
    try {
        FileWriter fw = null;
        BufferedWriter bw = null;
        BufferedReader in = null;
        for (Map.Entry<File, File[]> es : filesToWrite.entrySet()) {
            File temp = new File(es.getKey() + ".temp");
            bw = new BufferedWriter(new FileWriter(temp));
            for (File t : es.getValue()) {
                bw.write(readFile(t.getAbsolutePath()));
            }
            in = new BufferedReader(new FileReader(new File(es.getKey() + ".temp")));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                if (!line.contains("**** LOGGEN") && !line.contains("**** LOGGING")) {
                    sb.append(line);
                }
            }
            bw = new BufferedWriter(new FileWriter(es.getKey()));
            in.close();
            new File(es.getKey() + ".temp").delete();
            bw.write(sb.toString());
        }
    } catch (IOException e) {

    }
}

private static String readFile(String path) throws IOException {
    System.out.println("reading " + path);
    FileInputStream stream = new FileInputStream(new File(path));
    try {
        FileChannel chan = stream.getChannel();
        MappedByteBuffer mbb = chan.map(FileChannel.MapMode.READ_ONLY, 0, chan.size());
        return Charset.defaultCharset().decode(mbb).toString();
    } finally {
        stream.close();
    }
}
}

非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-01 02:20:24

你必须关闭缓冲的写入器:

之后..。

代码语言:javascript
复制
 bw = new BufferedWriter(new FileWriter(es.getKey()));
 in.close();
 new File(es.getKey() + ".temp").delete();
 bw.write(sb.toString());

添加

代码语言:javascript
复制
 bw.close();

如果缓冲的写入器没有关闭,更改将不会被保存,这解释了你提到的“(它忘记文本)”。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11746392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档