gpt4 book ai didi

Java 重命名不起作用

转载 作者:行者123 更新时间:2023-12-01 12:02:27 24 4
gpt4 key购买 nike

这是我的代码

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。代码输出重命名操作失败。之前在程序中使用过几乎完全相同的编辑代码,并且它有效。

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

最佳答案

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

 oldFileName.renameTo(newFileName);
if (oldFileName.renameTo(newFileName))

您正在尝试重命名两次。第一个可能会通过,但第二个肯定会失败。检查原文件是否被重命名。如果抛出任何错误,请记录堆栈跟踪并将跟踪添加到您的帖子中。

关于Java 重命名不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27898203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com