使用Java打开或关闭打开的Windows文件
问题描述:
我是新来的Stackoverflow和一般编程论坛,所以请原谅我,如果我没有发布我的问题,如预期:)。使用Java打开或关闭打开的Windows文件
我也尝试搜索一个小时的答案,并出乎意料地找不到任何有用的东西。
我正在编写一个代码,通过使用inputfilestream将Windows文件移动到另一个文件夹。问题是,当在Windows打开文件(并且它在某些情况下)打开一个新文件并将其分配给输入文件流失败时:
java.io.FileNotFoundException:C:\ Users \ N \桌面\源\ Doc1.docx(系统找不到指定的文件)
在java.io.FileInputStream.open(本机方法)
在java.io.FileInputStream.init>(来源不明)
所以我想到,试图打开一个文件流,我必须确保它关闭。 但我找不到通过Java代码关闭Windows文件的方式。 所有我能找到的都被认为是java.nio.File,它是虚拟的并且没有close方法。我该怎么做? 任何人都可以帮我找到这样的行动的参考?
我的相关代码段:
private void moveFileToFolder(File sourceDir, File destDir, Path prevFileName, String newFileName){
InputStream inStream = null;
OutputStream outStream = null;
byte[] buffer = new byte[1024];
int length;
try{
try{ //wait so windows can close file successfully
//(if it was opened as a new file and then closed automatically) before trying to read from it
wait(1000);
}catch(Exception e){}
File source =new File(sourceDir.getPath() + "\\" + prevFileName);
File dest =new File(destDir.getPath() + "\\" + newFileName);
inStream = new FileInputStream(source);
outStream = new FileOutputStream(dest);
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
source.delete();
if (DEBUG_MODE){
System.out.println("File was copied successfully!");
}
}catch(IOException e){
e.printStackTrace();
}
}
非常感谢您! Noa
答
如果打开一个文件,您将无法通过Java关闭它,因为要关闭它,您必须在Java代码中打开该文件。
您可以做的是创建一个列表并添加所有失败的文件,然后在处理结束时再次尝试处理这些文件。
如果仍然失败,用户可能会使用它,所以提示用户帮助或将其记录到日志文件以便用户可以获取有关文件未处理的信息是很有趣的。
答
开关闭和使用Java删除窗口的文件...
final File file=new File("E:\\features.xlsx");
//open file
if(file.exists())
Runtime.getRuntime().exec("cmd /c start E:\\"+file.getName());
//close and delete a open file
Runtime.getRuntime().exec(
"cmd /c taskkill /f /im excel.exe"); //put "winword.exe" for ms word file
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(2000);
file.delete();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();