无法删除/重命名文件

时间:2014-12-16 17:46:22

标签: java arrays

我想用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 个答案:

答案 0 :(得分:0)

您不需要临时文件。根据经验,我只会写文件,如果我要关闭我的程序,重新打开它并期望所述数据。我会将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)