我正在使用文本文件创建简单的地址簿,但是我的代码在删除字符串的方法中抛出了太多的错误。在大多数地方显示IO异常,当IO异常被解决后,编译错误在一些标识符中的5个地方出现了找不到符号。 下面是我的代码:
public void DeletePerson(){
try {
File file = new File("AddressBook.txt");
File temp = File.createTempFile("file", ".txt", file.getParentFile());
BufferedReader reader = new BufferedReader(new InputStreamReader(new
FileInputStream(file), Charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new
FileOutputStream(temp), Charset));
//More code ...
} finally {
if (writer != null) {
System.out.println("Closing PrintWriter");
writer.close();
} else {
System.out.println("PrintWriter not open");
}
file.delete();
temp.renameTo(file);
}
}
输出:
C:\java\AddressBook>javac AddressBook.java
AddressBook.java:50: error: cannot find symbol
if (writer != null) {
^
symbol: variable writer
location: class AddressBook
AddressBook.java:52: error: cannot find symbol
writer.close();
^
symbol: variable writer
location: class AddressBook
AddressBook.java:57: error: cannot find symbol
file.delete();
^
symbol: variable file
location: class AddressBook
AddressBook.java:58: error: cannot find symbol
temp.renameTo(file);
^
symbol: variable file
location: class AddressBook
AddressBook.java:58: error: cannot find symbol
temp.renameTo(file);
^
symbol: variable temp
location: class AddressBook
我正在创建通讯录,并在删除人名的方法中发现问题。 首先,我必须从用户输入,即人的姓名,然后我必须检查文本文件(阅读文件)和找到匹配的词,然后删除它从地址簿。 我也做了其他的方法删除名字,但他们没有彻底工作。 请检查代码并解决问题。
您可以尝试使用try
块内的file
和PrintWriter
对象。
File file = new File("AddressBook.txt");
PrintWriter writer = new PrintWriter(new FileWriter(file,Charset.forName("UTF-8")));//use "throws IOException" in your method.
try{
//some java code
}finally{
if (writer != null) {
System.out.println("Closing PrintWriter");
writer.close();
} else {
System.out.println("PrintWriter not open");
}
file.delete();
}