删除文本文件java不起作用

时间:2013-12-30 15:25:55

标签: java eclipse

以下是示例:

    public static void main (String[] args){
    String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
    String temppath = "C:\\Users\\Charbel\\Desktop\\temp.txt";
    File file = new File(path);
    File tempfile = new File(temppath);
    int numl = search("x");
    int countL = 0;
    String line;

    try {
        BufferedReader bf = new BufferedReader(new FileReader(path));
        BufferedWriter bw = new BufferedWriter(new FileWriter(temppath));

        while (( line = bf.readLine()) != null)
        {
            if(countL != numl){

            bw.write(line);
            bw.newLine();

            }

        countL++;
        }
        bf.close();
        bw.close();
        file.delete();
        boolean successful = tempfile.renameTo(file);
        System.out.println(successful);
    }
    catch (IOException e) {
        System.out.println("IO Error Occurred: " + e.toString());
    }



    }
    public static int search(String name) 
    {
        String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
        int countL = 0;
        String line;

        try {
        BufferedReader bf = new BufferedReader(new FileReader(path));

        while (( line = bf.readLine()) != null)
        {
                int indexfound = line.indexOf(name);

                if (indexfound == 0) {
                   return countL;
                }
                countL++;
        }

        bf.close();
    }
        catch (IOException e) {
            System.out.println("IO Error Occurred: " + e.toString());
        }

        return -1;

    }
    }

你好..我正在尝试读取文本文件中特定字符串的行,获取其行号,然后将文件中的所有数据复制到另一个文本文件,但字符串行除外 代码有时工作100%,有时没有;我转到我的桌面我看到两个文件的临时文件和原始文件没有删除和重命名 我认为我在删除文件时遇到问题您认为编码员会怎样?

1 个答案:

答案 0 :(得分:0)

因为当搜索方法找到名称(实际上是“x”)时,不要到达行bf.close(),所以仍然打开bf并且file.delete()失败。 因此,您需要将搜索方法修改为以下内容:

public static int search(String name) {
    String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
    int countL = 0;
    String line;

    BufferedReader bf = null;
    try {
        bf = new BufferedReader(new FileReader(path));

        while (( line = bf.readLine()) != null)
        {
            int indexfound = line.indexOf(name);

            if (indexfound == 0) {
                return countL;
            }
            countL++;
        }
    }
    catch (IOException e) {
        System.out.println("IO Error Occurred: " + e.toString());
    }
    finally {
        if(bf != null) {
            try {
                bf.close();
            }
            catch(IOException ignored) {}
        }
    }
    return -1;
}