无法使用delete()删除文本文件

时间:2015-11-06 09:53:03

标签: java

我正在尝试将数据从旧文本文件传输到新文本文件。虽然下面的代码能够成功传输,但它不会删除旧的文本文件。我可以知道为什么会这样吗?

private void dataTransfer(String oldFilePath, String newFilePath) {

        byte[] buffer = new byte[10000];
        try {
            FileInputStream fileInput = new FileInputStream(oldFilePath);
            BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
            FileOutputStream fileOutput = new FileOutputStream(newFilePath);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
            while(true) {
                int length = fileInput.read(buffer);
                if(length == -1) {
                    break;
                } else {
                    bufferedOutput.write(buffer);
                    bufferedOutput.flush();
                }   
            }
            fileInput.close();
            bufferedInput.close();
            fileOutput.close();
            bufferedOutput.close();
            File oldFile = new File(oldFilePath);
            oldFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(ERROR_TRANSFER_DATA);
        }

    }

5 个答案:

答案 0 :(得分:0)

要删除文件,它应该可以正常工作,但是要删除目录,您必须确保目录为空。

答案 1 :(得分:0)

更新JRE和JDK,确保您拥有该文件的权限。尝试使用您创建的文件。

另外,为SecurityException添加一个catch块

答案 2 :(得分:0)

根据Oracle的文档,delete方法不保证它会删除该文件。 http://docs.oracle.com/javase/7/docs/api/java/io/File.html#delete()

如果符合以下条件,删除文件将失败:

  • 文件不存在
  • 该文件存在锁定,可能由另一个进程打开
  • 文件在磁盘上不存在
  • 您没有足够的权限来删除该文件(在这种情况下会抛出SecurityException)

答案 3 :(得分:0)

您可以使用以下代码块。虽然不知道但它确实有效。即使没有setWritable,也可以,

oldFile.setWritable(true);
if(!oldFile.delete()){
     System.out.println("de;eted");
 }

答案 4 :(得分:0)

我同意@panagdu您可能没有足够的权利删除该文件。

就像侥幸一样,在fileInputStream

之前尝试关闭bufferedStream

bufferedInput.close();
fileInput.close();
bufferedOutput.close();
fileOutput.close();

但我不认为这会有所帮助。

使用足够的权限测试代码中的文件。例如,Java不允许对系统文件执行delete()。

相关问题