无法重命名文件

时间:2012-06-28 08:56:34

标签: java file file-rename

我正在尝试从不以特定字符串开头的文件中删除行。 我们的想法是将所需的行复制到临时文件,删除原始文件并将临时文件重命名为原始文件。

我的问题是我无法重命名文件!

tempFile.renameTo(new File(file))

tempFile.renameTo(inputFile)

不起作用。

谁能告诉我出了什么问题?这是代码:

/**
 * The intention is to have a method which would delete (or create
 * a new file) by deleting lines starting with a particular string. *
 */
package com.dr.sort;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class RemoveLinesFromFile {

    public void removeLinesStartsWith(String file, String startsWith, Boolean keepOrigFile) {
        String line = null;
        BufferedReader rd = null;
        PrintWriter wt = null;
        File tempFile = null;

        try {
            // Open input file
            File inputFile = new File(file);

            if (!inputFile.isFile()) {
                System.out.println("ERROR: " + file + " is not a valid file.");
                return;
            }

            // Create temporary file

            tempFile = new File(file + "_OUTPUT");

            //Read input file and Write to tempFile

            rd = new BufferedReader(new FileReader(inputFile));
            wt = new PrintWriter(new FileWriter(tempFile));
            while ((line = rd.readLine()) != null) {
                if (line.substring(0, startsWith.length()).equals(startsWith)) {
                    wt.println(line);
                    wt.flush();
                }

            }
            rd.close();

            if (!keepOrigFile) {

                inputFile.delete();

                if (tempFile.renameTo(new File(file))) {
                    System.out.println("OK");
                } else {
                    System.out.println("NOT OK");
                }
            }

        }

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

        finally {
            if (tempFile != null && tempFile.isFile()) {
                wt.close();
            }
        }

    }
}

2 个答案:

答案 0 :(得分:5)

我猜你需要在重命名之前关闭你的PrintWriter

答案 1 :(得分:0)

if (line.substring(0, startsWith.length()).equals(startsWith)) 

应该相反,因为我们不希望包含指定的行。 这样:

if (!line.substring(0, startsWith.length()).equals(startsWith))