java - 简单的文件删除代码在 Java 中不起作用

标签 java file delete-file

这是我删除pdf文件的代码

try {
    File file = new File(docObjectId + ".pdf");
    file.setWritable(true);
    System.out.println(file.length());
    if (file.delete()) {
        System.out.println(file.getName() + " is deleted!");
    } else {
        System.out.println("Delete operation is failed.");
    }
} catch (Exception e) {
    e.printStackTrace();
}

它转到代码的 else 部分。

PDF 文件位于项目根文件夹中,我可以手动删除它。现在正在挠头。

这是完整的方法。可能是由于其他原因

public Response getContractDocument(@PathParam("docid") String docObjectId) throws Exception {
    DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
    DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);

    FileInputStream fileInputStream;
    fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
    compressPdf(fileInputStream,docObjectId + ".pdf");

    fileInputStream = new FileInputStream(docObjectId + ".pdf");


    ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
    try {
        File file = new File(docObjectId + ".pdf");
        System.out.println(file.getAbsolutePath());
        file.setWritable(true);
        System.out.println(file.length());

        File d = new File(file.getAbsolutePath());
        if (d.delete()) {
            System.out.println(file.getName() + " is deleted!");
        } else {
            System.out.println("Delete operation is failed.");
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
    return responseBuilder.build();
}

最佳答案

我的经验是使用Windows。文件无法删除的原因总是相同的。某些对象与该文件有连接并使其保持打开状态。在本例中,看起来可能是 fileInputStream。

在尝试删除之前请尝试以下操作:

fileInputStream.close();

关于java - 简单的文件删除代码在 Java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45725384/

相关文章:

python - 使用 ZipFile 模块从 zipfile 中删除文件

java - 当前线程的事务同步 session Hibernate4 异常 spring 4

java - 从集合类及其存储的对象中获取 StackOverflowError。有没有人有过类似的困境?

创建有错误的文件

java - 在 netbeans 中打开文件

ruby - 使用 Ruby SFTP 删除文件 `remove` 和 `remove!`

java - Tomcat 在请求完成时删除文件?

java - 为什么有些 java 库被排除在 android sdk 之外?

java - 线程和可变参数

c - 当/dev/ttyUSB* 出现时打开它