繁体   English   中英

重命名和删除文件

[英]Renaming and deleting files

我正在编写一个程序来查找信息,方法是制作一个临时文件,删除原始文件,然后将临时文件重命名为原始文件,并将其从文本文件中删除。 到目前为止,我已经完成了编写程序的工作,并且在使用Windows控制台编译该程序时它可以工作,但是当我尝试在netbeans中运行相同的代码时,它无法工作,因为它无法删除和重命名原始文件。 我正在寻找解决此问题的方法。

这是代码,当我使用Windows控制台而不是在netbeans中进行编译时,它可以工作

import java.io.*;

public class rename {
public static String x="1123";

public void removeLineFromFile(String file, String lineToRemove) {

try {

  File inFile = new File(file);

  if (!inFile.isFile()) {
    System.out.println("Parameter is not an existing file");
    return;
  }

  //Construct the new file that will later be renamed to the original filename. 
  File tempFile = new File(inFile.getAbsolutePath() + "2.tmp");

  BufferedReader br = new BufferedReader(new FileReader(file));
  PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

  String line = null;

  //Read from the original file and write to the new 
  //unless content matches data to be removed.
  while ((line = br.readLine()) != null) {

    if (!line.trim().contains(lineToRemove)) {

      pw.println(line);
      pw.flush();
    }
  }
  pw.close();
  br.close();

  //Delete the original file
  if (!inFile.delete()) {
    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();
}
}

public static void main(String[] args) {
rename util = new rename();
String jj;
util.removeLineFromFile("File.txt", x);
}
}

哼...关闭brpw ,尝试将它们设置为null并调用System.gc()

参考: 我无法在Java中删除文件

重命名

  public void rename(String old, String newpath) {
    try {
        File folder = new File(old);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {

                File f = new File(old + listOfFiles[i].getName());

                f.renameTo(new File(old + "\\" + newpath));

                System.out.println(old + "\\" + newpath);
            }
        }

        System.out.println("conversion is done");

    } catch (Exception ex) {
        Logger.getLogger(CVAdd.class.getName()).log(Level.SEVERE, null, ex);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM