Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 一种编程分配,如果多个文件的名称匹配,则将其合并为一个文件。FileWriter/BufferedWriter_Java - Fatal编程技术网

Java 一种编程分配,如果多个文件的名称匹配,则将其合并为一个文件。FileWriter/BufferedWriter

Java 一种编程分配,如果多个文件的名称匹配,则将其合并为一个文件。FileWriter/BufferedWriter,java,Java,好的,我要做一个作业: 假设您有如下分类的聊天日志: 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/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/#频道与System-1/#频道日志文件合并?我已经找到了获取它们的方法,但是BufferedWriter会随机停止写入(它会忘记文本),并且只对1个文件有效(因此,假设不同目录中有2个重复的日志文件,它只会处理不同目录中的第一个重复日志文件)

对不起,我的英语不是以英语为母语的,但我希望你能理解我的意思。到目前为止,我所拥有的是:我也愿意接受任何改进

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();
    }
}
}
import java.io.*;
导入java.nio.MappedByteBuffer;
导入java.nio.channels.FileChannel;
导入java.nio.charset.charset;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.Map;
导入java.util.logging.Logger;
公共类合并v2{
私有静态最终记录器log=Logger.getLogger(MergeV2.class.getName());
私有静态最终文件根目录=新文件(System.getProperty(“user.home”)+(System.getProperty(“os.name”)。包含(“Windows”)?“/AppData/Roaming/X-Chat 2/xchatlogs”:“/.xchat2/xchatlogs”);
私有静态最终HashMap文件=新HashMap();
private static final HashMap filesToWrite=new HashMap();
公共静态void main(字符串…参数){
如果(根目录文件夹.exists()){
对于(最终文件f:ROOT\u FOLDER.listFiles()){
如果(f.isDirectory()&&f.getName()包含(“系统”){//强制检查
对于(最终文件子文件:f.listFiles()){
字符串channelName=sub.getName().split(“#”)[1]。replaceAll(“.log”,”);
if(files.containsKey(channelName)){
ArrayList tempFiles=新建ArrayList();
for(文件t:files.get(channelName)){
tempFiles.add(t);
}
tempFiles.add(sub);
File[]数组=新文件[tempFiles.size()];
array=tempFiles.toArray(数组);
put(channelName,array);
}否则{
put(channelName,新文件[]{sub});
}
}
}
}
}否则{
log.info(“未检测到日志文件夹”);
}
串通道;
文件f,ftemp;
对于(Map.Entry es:files.entrySet()){
channel=“#”+es.getKey();
f=新文件(根文件夹.getAbsolutePath()+”/merged-“+channel+”.log”);
ftemp=新文件(f.getAbsolutePath()+“.temp”);
如果(f.exists()){
f、 删除();
ftemp.delete();
}
试一试{
f、 createNewFile();
ftemp.createNewFile();
}捕获(ioe异常ioe){
ioe.printStackTrace();
}
filesToWrite.put(f,es.getValue());
}
试一试{
FileWriter fw=null;
BufferedWriter bw=null;
BufferedReader in=null;
对于(Map.Entry es:filesToWrite.entrySet()){
File temp=新文件(es.getKey()+“.temp”);
bw=新的缓冲写入程序(新的文件写入程序(临时));
对于(文件t:es.getValue()){
write(readFile(t.getAbsolutePath());
}
in=new BufferedReader(新文件读取器(新文件(es.getKey()+“.temp”));
StringBuilder sb=新的StringBuilder();
弦线;
而((line=in.readLine())!=null){
如果(!line.contains(“*****LOGGEN”)和(&!line.contains(“*****LOGGING”)){
某人附加(行);
}
}
bw=新的BufferedWriter(新的文件编写器(es.getKey());
in.close();
新文件(es.getKey()+“.temp”).delete();
写(sb.toString());
}
}捕获(IOE异常){
}
}
私有静态字符串读取文件(字符串路径)引发IOException{
System.out.println(“读取”+路径);
FileInputStream=新FileInputStream(新文件(路径));
试一试{
FileChannel chan=stream.getChannel();
MappedByteBuffer mbb=chan.map(FileChannel.MapMode.READ_ONLY,0,chan.size());
返回Charset.defaultCharset().decode(mbb.toString();
}最后{
stream.close();
}
}
}

非常感谢

您必须关闭缓冲写入程序:

之后


如果缓冲写入程序未关闭,更改将不会保存,这就解释了您提到的“(它会忘记文本)”。

谢谢,这稍微修复了它,但它仍然跳过大约100行。您是否使用过fw,FileWriter fw=null;不会导致任何错误,只是指出无法找到任何其他错误,是否可能出现异常,请尝试打印出一些内容
 bw = new BufferedWriter(new FileWriter(es.getKey()));
 in.close();
 new File(es.getKey() + ".temp").delete();
 bw.write(sb.toString());
 bw.close();