public void run() {
WatchService watchService;
try {
watchService = FileSystems.getDefault().newWatchService();
Paths.get(watchedPath).register(watchService,
StandardWatchEventKinds.ENTRY_CREATE);
while(true)
{
WatchKey key=watchService.take();
for(WatchEvent<?> event:key.pollEvents())
{
WatchEvent ev = cast(event);
Path name = ev.context();
if(ftpUser == null || ftpUser.equals("")){ //本地local
FtpUtil.copyFile(name.toFile(),localPath,watchedPath);
}else{
// FtpUtil.uploadFile(name.toFile(), localPath, "ftp.properties",watchedPath); //ftp
FtpUtil.uploadFile(name.toFile(), localPath, ftpUser,watchedPath); //ftp
}
}
boolean reset = key.reset();
if (!reset)
break;
}
} catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 复制单个文件
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public static void copyFile(File newFile, String newPath,String oldPath) {
InputStream inStream = null;
FileOutputStream fs = null;
try {
int bytesum = 0;
int byteread = 0;
String filePath = oldPath +"\\"+newFile;
File oldfile = new File(filePath);
if (oldfile.exists()) { // 文件存在时
inStream = new FileInputStream(filePath); // 读入原文件
fs = new FileOutputStream(newPath+"\\"+newFile);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
fs.write(buffer, 0, byteread);
}
System.out.println("aaa");
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}finally{
try {
if(null!=fs){
fs.close();
}
if(null!=inStream){
inStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("bbb");
}
}
java.io.FileNotFoundException: D:\text1\新建文本文档 (2).txt (另一个程序正在使用此文件,进程无法访问。)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:138)
at java.io.FileInputStream.(FileInputStream.java:97)
at com.rihang.util.FtpUtil.copyFile(FtpUtil.java:143)
at com.rihang.publicserviceproduct.FileWatcherThread.run(FileWatcherThread.java:68)
上边是代码和异常,我要做的是,当监控的目录下多了一个文件的时候就将该文件copy 到其他目录下。现在第一次没问题。第二次在放如监控目录下一个文件时就提示这个异常。但是我如果在inStream = new FileInputStream(filePath); 这行打个断点停顿下就没这个问题了。在线求解。