如何在Java中关闭和删除文件

时间:2015-03-23 09:01:57

标签: java

我编写的代码应该保存在本地目录中,创建该文件的zip,发送电子邮件并删除这两个文件(原始文件和zip文件),所以这是我的代码:

发送电子邮件的方法

public void sendEmail(Properties emailProperties, InputStream inputStream, HttpServletRequest request) throws UnsupportedEncodingException {


    MimeMessage mimeMessage = mailSender.createMimeMessage();
    try {
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        try {
            mimeMessageHelper.setFrom(from, personal);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage());
            throw new SequelException(e.getMessage());
        }

            mimeMessageHelper.setTo(recipients);
            mimeMessageHelper.setSubject(emailProperties.getProperty(PARAM_TITLE));             
            String message = emailProperties.getProperty(PARAM_EMLMSG);         
            mimeMessageHelper.setText(message);


            InputStreamSource inputStreamSource = null;
            if (inputStream != null) {
                inputStreamSource = new ByteArrayResource(IOUtils.toByteArray(inputStream));
            } 

            String compressType = COMPRESS_TYPE_ZIP;
            String fileName = getAttachFilenameExtension(object, format);
            Path filePath = Paths.get(StrUtils.getProperty("temp.email.files.path") + "\\" + fileName);
            tempFile = saveTempFile(inputStreamSource.getInputStream(), filePath);
            if (tempFile.length() > 0) {
                inputStreamSource = compressFile(tempFile, filePath.toString(), compressType);
                fileName = StringUtils.substring(fileName, 0, StringUtils.lastIndexOf(fileName, ".")+1)  + compressType;
            }

            mimeMessageHelper.addAttachment(fileName, inputStreamSource);
            mailSender.send(mimeMessage);


    } catch (MessagingException | IOException e) {
        LOGGER.error(e.getMessage());
        throw new SequelException(e.getMessage());
    } finally {
        List<File> files = (List<File>) FileUtils.listFiles(tempFile.getParentFile(), new WildcardFileFilter(
                FilenameUtils.removeExtension(tempFile.getName()) + "*"), null);
        for (File file : files) {
            try {
                FileUtils.forceDelete(file);
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
        }
    }
} 

将文件保存在目录中:

private File saveTempFile(InputStream inputStream, Path filePath) throws IOException {
    Files.deleteIfExists(filePath);
    Files.copy(inputStream, filePath);
    return new File(filePath.toString());
}

压缩文件:

private InputStreamSource compressFile(File file, String filePath, String compressType) throws IOException {
    InputStream is = ZipFile(file, filePath);
    InputStreamSource inputStreamSource = new ByteArrayResource(IOUtils.toByteArray(is));
    return inputStreamSource;
}

public InputStream ZipFile(File file, String filePath) {
    String zipArchiveFileName = StringUtils.substring(filePath, 0, filePath.lastIndexOf(".") + 1) + COMPRESS_TYPE_ZIP;

    try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File(zipArchiveFileName));) {
        ZipArchiveEntry entry = new ZipArchiveEntry(StringUtils.overlay(file.getName(), "",
                StringUtils.lastIndexOf(file.getName(), "_"), StringUtils.lastIndexOf(file.getName(), ".")));
        zipOutput.putArchiveEntry(entry);
        try (FileInputStream in = new FileInputStream(file);) {
            byte[] b = new byte[1024];
            int count = 0;
            while ((count = in.read(b)) > 0) {
                zipOutput.write(b, 0, count);
            }
            zipOutput.closeArchiveEntry();
        }

        InputStream is = new FileInputStream(zipArchiveFileName);
        return is;

    } catch (IOException e) {
        LOGGER.error("An error occurred while trying to compress file to zip", e);
        throw new SequelException(e.getMessage());
    }

}

所以问题是当我尝试删除文件但是zip文件没有删除时。 我正在使用Apache commons压缩来进行压缩。 你能帮忙解决什么问题吗?

1 个答案:

答案 0 :(得分:0)

对我来说,这段代码完美无缺。压缩后,您可能会尝试删除它而不使用扩展名(例如,此处为.7z)。

public static void main(String[] args) {
    File file = new File("C:\\Users\\kh1784\\Desktop\\Remote.7z");
    file.delete();
    if(!file.exists())
        System.out.println("Sucessfully deleted the file");
}

输出: -

  

成功删除了文件