Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从文本文件中删除字符串_Java_File_Io - Fatal编程技术网

Java 从文本文件中删除字符串

Java 从文本文件中删除字符串,java,file,io,Java,File,Io,这是我从文件中删除字符串的代码。 此代码从生成的临时文件中删除字符串 --但不要将原始文件替换为已编辑的临时文件 原始文件保持原样。在临时文件中进行编辑,但不会重命名为原始文件 try{ File inFile = new File("ext.txt"); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } File temp

这是我从文件中删除字符串的代码。 此代码从生成的临时文件中删除字符串 --但不要将原始文件替换为已编辑的临时文件


原始文件保持原样。在临时文件中进行编辑,但不会重命名为原始文件

 try{
    File inFile = new File("ext.txt");

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

  File tempFile = new File(inFile.getAbsolutePath()+".txt");

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

  String line = null;

    while ((line = br.readLine()) != null) {

    if (!line.trim().equals(mystring)) {

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

  }

  pw.close();
  br.close();
   inFile.delete();
   tempFile.renameTo(inFile);

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

    if (!tempFile.renameTo(inFile))
    System.out.println("Could not rename file");

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

您的代码运行得非常好。您需要存储布尔值file.delete和file.rename,并在“if”条件中使用这些值。该漏洞是,您正试图删除和重命名已重命名和删除的同一文件,因此它无法满足您的if条件。尝试这样做:

       boolean isDeleted = inFile.delete();
       boolean isRenamed = tempFile.renameTo(inFile);

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

        if (!isRenamed)
        System.out.println("Could not rename file");

你的问题是?请读最后一行。代码未将原始文件替换为已编辑的文件。原始文件保持原样。编辑是在临时文件中进行的,它不会重命名为原始文件。如果您有代码,请共享代码。谢谢。我已经解决了这个问题。通过将可写模式设置为true。