Java重命名不起作用

时间:2015-01-12 08:52:21

标签: java file netbeans

这是我的代码

private void edit(String search_bookname) {
    String current_bookname ="", current_ISBN = "", current_author = "", current_rating = "", record = "", comma = ",", current_status = "";
    int flag1 = 0, flag2 = 0;
    File file = new File("Book_data.txt");
    try {
        BufferedReader reader = new BufferedReader (new FileReader (file));
        File f = new File("Book_data_copy.txt");
        FileWriter create = new FileWriter(f);
        PrintWriter y = new PrintWriter(create);
        while(reader.ready())
        {
            record = reader.readLine();
            StringTokenizer st = new StringTokenizer(record, ",");
            while(st.hasMoreTokens()) {
                current_bookname = st.nextToken();
                current_author = st.nextToken();
                current_ISBN = st.nextToken();
                current_rating = st.nextToken();
                current_status = st.nextToken();
                flag2 = 0;
                if (search_bookname.equals(current_bookname)) {
                    flag1 = 1;
                    flag2 = 1;
                    try {
                        y.print(current_bookname); y.print(comma);
                        y.print(current_author); y.print(comma);
                        y.print(current_ISBN); y.print(comma);
                        y.print(current_rating); y.print(comma);
                        y.println("Borrowed");
                    } catch(Exception e) {}
                    Thread.sleep(1000);
                    }
             }
     if(flag2==0) // All non-matching records shall only be written to file. Record to be deleted will not be written to new file
                    {
                    y.print(current_bookname);  y.print(comma);      //One record per line.....   Each field in a record is seperated by COMMA (" , " )
                    y.print(current_author);  y.print(comma);
                    y.print(current_ISBN);  y.print(comma);
                    y.print(current_rating);y.print(comma);
                    y.println(current_status);
                     }
    }
        reader.close();
        y.close();
        create.close();
} catch (Exception e) {}
    if(flag1==1)     //Rename File ONLY when record has been found for Edit
    {
        File oldFileName = new File("Book_data_copy.txt");  
        File newFileName = new File("Book_data.txt");  
        System.out.println("File renamed .....................");
        try 
        {  
            newFileName.delete();  oldFileName.renameTo(newFileName);
            if (oldFileName.renameTo(newFileName)) 
           System.out.println("File renamed successfull !");  
            else    
            System.out.println("File rename operation failed !"); 
            Thread.sleep(1000);
} catch (Exception e) {}

    }
}

该项目适用于图书馆系统。我是java的新手,我在Windows 8.1上使用netbeans。代码输出重命名操作失败。几乎完全相同的编辑代码之前已经在程序中使用过了。

任何建议或代码更正都会有所帮助。 谢谢!

4 个答案:

答案 0 :(得分:2)

您的问题在于以下代码部分

 oldFileName.renameTo(newFileName);
            if (oldFileName.renameTo(newFileName)) 
你试图重命名两次。第一个可能会通过,但第二个肯定会失败。检查原始文件是否已重命名。如果在堆栈跟踪中抛出任何错误并将跟踪添加到您的帖子中。

答案 1 :(得分:0)

您正尝试重命名oldFileName两次:

newFileName.delete();  oldFileName.renameTo(newFileName); // rename
if (oldFileName.renameTo(newFileName)) // rename again ?!
    System.out.println("File renamed successfull !");  
else    
    System.out.println("File rename operation failed !"); 

if()中的第二次重命名失败,因为该文件已在之前的行中重命名。

答案 2 :(得分:0)

这里有许多问题,从忽略异常开始;没有关闭finally块中的文件;并错误地使用Reader.ready()

答案 3 :(得分:-1)

这是2015年。Use java.nio.file

final Path srcFile = Paths.get("Book_data.txt").toAbsolutePath();
final Path dstFile = srcFile.resolveSibling("Book_data_copy.txt");

try (
    final BufferedReader reader = Files.newBufferedReader(srcFile, StandardCharsets.UTF_8);
    final BufferedWriter writer = Files.newBufferedWriter(dstFile, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    final PrintWriter pw = new PrintWriter(writer);
) {
    // work with reader and pw
}

if (flag1 == 1)
    Files.move(dstFile, srcFile, StandardCopyOption.REPLACE_EXISTING,
        StandardCopyOption.ATOMIC_MOVE);

如果你从一开始就这样做了,不仅你的资源安全关闭(你的代码没有这样做),但你也会得到一个有意义的例外(你试图重命名两次;你会有在第二次重命名时有一个NoSuchFileException

Relying on File is an error,它一直都是。