我想知道如何将文件异步移动到其他位置, 基本上我的程序之一是继续将数据附加到临时文件而另一个是在超过临时文件的预定义大小时检查其大小应该将其复制到永久目录,并且前一个程序应该继续创建一个新的临时文件并继续写作,在复制的数据之间不应该丢失。 我尝试使用以下代码执行相同的操作,但有些数据错位或丢失。
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();
}
}
}
}
}