3

我想知道我们如何将文件异步移动到不同的位置,基本上我的一个程序是继续将数据附加到一个临时文件,另一个正在检查它的大小是否超过了它应该被复制到的临时文件的预定义大小一个永久目录和之前的程序应该不断的创建一个新的临时文件并继续写入,在这之间复制的数据不应该丢失。我尝试对下面的代码做同样的事情,但有些数据要么放错了地方,要么丢失了。

import java.io.*;
import org.apache.log4j.Logger;

public class FileSizeMonitor {

    static Logger log = Logger.getLogger(FileSizeMonitor.class.getName());
    private static final String tempDirectory = "c:\\my-temp-dir";
    private static final String tempFileName = tempDirectory + "\\" + "my-temp-file.txt";

    void FileMonitor() {
        File file = new File(tempFileName);
        double bytes = 0;
        if (file.exists()) {
            bytes = file.length();
            if (bytes > 2458.0001) {
                int length;
                byte[] buffer = new byte[1024];
                try {
                    InputStream inStream = null;
                    OutputStream outStream = null;

                    String source = tempFileName;
                    String target = "C:\\Users\\data";

                    File sourceFile = new File(source);
                    String fileName = sourceFile.getName();
                    File targetFile = new File(target + fileName);

                    inStream = new FileInputStream(sourceFile);
                    outStream = new FileOutputStream(targetFile);

                    log.debug("File size exceded the predefined limit,moving the file data to  C:\\Users\\data");

                    while ((length = inStream.read(buffer)) > 0) {
                        outStream.write(buffer, 0, length);
                    }

                    inStream.close();
                    outStream.close();

                    sourceFile.delete();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
4

0 回答 0