有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法删除/重命名文件

我想用tempFile的内容更新我的inputFile。。但它不允许我删除或重命名。。我需要帮助

try{
    reader = new BufferedReader(new FileReader(inputFile));
    out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile, true)));
    Scanner scan = new Scanner(System.in);
    String word = "";

    while(!word.contentEquals("exit")){
    System.out.println("Enter a command: ");
    word = scan.nextLine();
    String entries[] = word.split(" ");



        if(word.startsWith("add")){
            out.write(entries[1] + " " + entries[2]);
            out.write("\r\n");
        } else if (word.startsWith("remove")){
            String currentLine;
            while((currentLine = reader.readLine()) != null) {
                // trim newline when comparing with lineToRemove
                String trimmedLine = currentLine.trim();
                if(trimmedLine.contains(entries[1])) continue;
                //out.write(currentLine + System.getProperty("line.separator")); 
            }
        } else if (word.equals("show")){
            String currentLine;
            while((currentLine = reader.readLine()) != null) {
                // trim newline when comparing with lineToRemove
                System.out.println(currentLine); 
            }
        }
    }

    }
    finally {
        out.close();
        out.flush();
        reader.close();
        }

        //Delete the original file
    if (!inputFile.delete()) {
      System.out.println("Could not delete file");
      return;
    }

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

  }

我的整个程序应该在文件中添加联系人或条目。然后用户可以删除或显示文本文件中的所有联系人。还有其他方法吗?我可以覆盖该文件而不是使用临时文件吗?如果是,我怎么做

它总是显示“无法重命名文件”或“无法删除文件”


共 (1) 个答案

  1. # 1 楼答案

    您不需要临时文件。根据经验,只有当我要关闭程序、重新打开程序并期望收到所述数据时,我才会写入文件。我将out设为StringBuilder,并将每一行附加到它而不是文件。然后使用字符串生成器写回文件

    StringBuilder fileOutput = new StringBuilder();
    //your per line logic
    //instead of out.write() use fileOutput.append()
    System.out.println(String.format("File.canWrite() says %s", inputFile.canWrite());
    PrintWriter fileToWrite = new PrintWriter(inputFile);
    fileToWrite.println(fileOutput.toString());
    fileToWrite.close();
    

    如果要保存文件以前的内容,请在写入任何内容之前将以前的内容写入StringBuilder

    如果希望保存以前的数据,请使用此选项

    String current line = "";
    StringBuilder fileOutput = new StringBuilder();
    while((currentLine = reader.readLine()) != null) {
        fileOutput.append(currentLine)
    }
    //the rest of the code above (obviously don't set `fileOutput` twice though)