Asynchronous File copy in java

1.3k Views Asked by At

I want to know how we can move a file to a different location asynchronously, basically one of my program is keep on appending data to a temporary file and another is checking its size on exceeding the predefined size of the temporary file it should be copied to a permanent directory and the previous program should keep create a new temporary file and continue writing, in between the data copied should not lost. I tried to do the same with the following code but some of the data are either misplaced or lost.

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();
                }
            }
        }
    }
}
0

There are 0 best solutions below