无法在 Java 中删除文件,因为它正在 Java Platform SE 二进制文件中打开。
无法在 Java 中删除文件,因为它正在 Java Platform SE 二进制文件中打开。
我在Windows系统中有三个文件夹A、B和C。我有一个在文件夹A中存在的文件。我想要执行以下任务:
- 将其复制到文件夹B
- 从文件夹A中删除它(因为文件不被任何进程占用,所以此步骤可以完成)
- 将其复制到文件夹C
- 从文件夹B中删除它(这一步不起作用)
第1、2、3步骤可行,但第4步骤却不行。该文件存在并且可以读取、写入、执行。我打开Windows资源管理器并尝试手动删除文件夹B中的文件时,它显示操作无法完成,因为它在Java平台SE二进制文件中打开。下面是我复制文件的代码:
FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close();
我正在使用Java 6。你知道我如何完成第4步吗?
admin 更改状态以发布 2023年5月23日
试试这个:
代码
public void foo(){ File afile =new File("A\\Afile.txt"); File bfile =new File("B\\Bfile.txt"); InputStream inStream = new FileInputStream(afile); OutputStream outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); System.out.println("File Copied"); if(afile.delete()){ System.out.println(file.getName() + " deleted!"); }else{ System.out.println("Delete failed."); } }
请确保您使用适当的try和catch子句
为什么不使用类似Apache Commons IO(FileUtils)的库呢?
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
File a = new File("A/file.txt"); File b = new File("B/file.txt"); File c = new File("C/file.txt"); FileUtils.copyFile(a, b); a.delete(); FileUtils.copyFile(b, c); b.delete();