JAVA.io文件剪切/删除问题

JAVA.io文件剪切/删除问题

在实现文件剪切的过程中,我发现无法删除原文件。

FileOutputStream fos = null;
FileInputStream fis = null;
File file = null;

try{
    file = new File("C:\\666.docx");
    fis = new FileInputStream(file);
    fos = new FileOutputStream("C:\\777.docx");

    byte[] bytes = new byte[1024];

    while(fis.read(bytes) != -1){
        fos.write(bytes);
    }

    if(file.exists() && file.delete()) System.out.println("!");
    else{
        System.out.println("?");
    }

}catch (Exception e){
    System.out.println(e);
}finally {
    try {
        if(fis != null) fis.close();
        if(fis != null) fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

查阅相关资料,发现delete需要先关闭流后,再进行删除(资源被占用,导致其他对象无法访问此资源)。文件剪切代码逻辑不够严禁。此处仅讨论delete一个文件问题。

FileOutputStream fos = null;
FileInputStream fis = null;
File file = null;

try{
    file = new File("C:\\666.docx");
    fis = new FileInputStream(file);
    fos = new FileOutputStream("C:\\777.docx");

    byte[] bytes = new byte[1024];

    while(fis.read(bytes) != -1){
        fos.write(bytes);
    }

}catch (Exception e){
    System.out.println(e);
}finally {
    try {
        if(fis != null) fis.close();
        if(fis != null) fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if(file.exists() && file.delete()) System.out.println("!");
    else{
        System.out.println("?");
    }
}
Java中,操作文件通常涉及到I/O(输入/输出)API,特别是`java.io`包下的类,如`File`, `BufferedReader`, 和 `FileWriter`等。剪切文件,也就是复制并删除文件的操作,可以分为两步:首先复制文件内容到目标位置,然后删除文件。 以下是一个简单的示例,演示如何使用Java实现文件剪切: ```java import java.io.*; public class FileCopyAndDelete { public static void main(String[] args) { try { // 定义源文件和目标文件路径 String sourceFilePath = "src.txt"; String destinationFilePath = "dest.txt"; // 检查文件是否存在 File srcFile = new File(sourceFilePath); if (!srcFile.exists()) { System.out.println("Source file not found."); return; } // 创建目标文件的目录(如果不存在) File destDir = new File(destinationFilePath).getParentFile(); if (!destDir.exists() && !destDir.mkdirs()) { System.out.println("Failed to create destination directory."); return; } // 读取源文件 BufferedReader reader = new BufferedReader(new FileReader(srcFile)); StringBuilder content = new StringBuilder(); // 将文件内容逐行添加到StringBuilder String line; while ((line = reader.readLine()) != null) { content.append(line + "\n"); } reader.close(); // 写入目标文件 BufferedWriter writer = new BufferedWriter(new FileWriter(destinationFilePath)); writer.write(content.toString()); writer.close(); // 删除文件 srcFile.delete(); System.out.println("File copied and source deleted."); } catch (IOException e) { System.err.println("An error occurred: " + e.getMessage()); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值