首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java编程中文件的删除与重命名

Java编程中文件的删除与重命名
EN

Stack Overflow用户
提问于 2012-04-15 03:12:46
回答 2查看 774关注 0票数 0

我需要在删除和重命名Java编程中的文件帮助。我的问题是原始文件不能删除,第二个文件不能重命名。以下是代码片段。任何建议都将不胜感激。

代码语言:javascript
复制
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;




public void deleteLine(String content) {
    try {

        File inFile = new File("football.dat");
        if (!inFile.isFile()) {
            System.out.println("Parameter is not an existing file");
            return;
        }
        File tempFile = new File(inFile.getAbsolutePath() + "2");
        BufferedReader br = new BufferedReader(new FileReader(inFile));
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile), true);

        String linetobeempty = null;
        while ((linetobeempty = br.readLine()) != null) {

            if (!linetobeempty.trim().equals(content)) {
                pw.println(linetobeempty);
                pw.flush(); System.out.println(linetobeempty);
            }
        }

        pw.close();        
        br.close();
       boolean b = inFile.delete();

        if (!b) {
            System.out.println("Could not delete file");
            return;
        }

        //Rename the new file to the filename the original file had.
        if (!tempFile.renameTo(inFile)) {
            System.out.println("Could not rename file");
        }


    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
EN

回答 2

Stack Overflow用户

发布于 2012-04-15 03:51:33

此代码片段中没有任何内容会直接导致文件未被删除。问题在于更深层次的问题--权限,由其他进程打开,以及一些常见的东西。检查所有这些。当然,删除失败后重命名失败的原因是显而易见的,所以目前您只知道一个问题。

票数 1
EN

Stack Overflow用户

发布于 2012-04-15 04:35:06

您使用的是Windows吗?在Windows上,如果任何进程在文件上具有文件句柄,则取消链接和重命名将失败(与UNIX不同)。我甚至注意到,在用Java进行文件I/O测试时,有时需要让操作系统在写入文件和删除文件之间稍作休息。renameTo and delete上的文档给出了一些有限的见解。

要简化问题并更好地调试它,只需创建文件而不是写入文件--使用File.createNewFile()。

您可能会遇到与Cannot delete file Java相同的问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10156524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档