5 回答
TA贡献1804条经验 获得超7个赞
有两种解决方案:
不要关闭扫描仪。保持其打开状态,直到不需要为止。换句话说,在循环之后关闭它。
通过调用 重新创建扫描仪
sc = new Scanner(new File("addressBook.txt"));
。但是,由于这将创建一个新的扫描仪,因此它将再次从第一行开始读取。
TA贡献1802条经验 获得超5个赞
您的主要问题是您deleteByName()
在循环内调用删除原始文件然后重用Scanner
.
你应该这样做:
找到所有
name
呼叫
deleteByName()
与所有发现names
。
public final class AddressBookManager {
private final File file;
public AddressBookManager(File file) {
this.file = file;
}
public void modifyContact(String oldName, String newName) throws IOException {
if (isContactExists(oldName))
updateContactName(oldName, newName);
}
private boolean isContactExists(String name) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
while (scan.hasNextLine()) {
String str = scan.nextLine();
if (str.startsWith(name + ',')) {
String[] parts = str.split(",");
System.out.format("Contact found. Name '%s', phone number '%s', address '%s', email '%s'\n", parts[0], parts[1], parts[2],
parts[3]);
return true;
}
}
System.out.println("No contact found with name '" + name + '\'');
return false;
}
}
private void updateContactName(String curName, String newName) throws IOException {
File tmp = new File(file.getParent(), "TempFile.txt");
try (BufferedReader in = new BufferedReader(new FileReader(file));
BufferedWriter out = new BufferedWriter(new FileWriter(tmp))) {
String str;
while ((str = in.readLine()) != null) {
if (str.startsWith(curName))
str = newName + str.substring(str.indexOf(','));
out.write(str);
out.newLine();
}
}
System.out.println("remove old file: " + file.delete());
System.out.println("rename temp file: " + tmp.renameTo(file));
}
public static void main(String... args) throws IOException {
AddressBookManager addressBookManager = new AddressBookManager(new File("d:/addressBook.txt"));
String curName = "oleg";
String newName = getNewName(curName);
addressBookManager.modifyContact(curName, newName);
}
private static String getNewName(String curName) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter new name for (" + curName + "): ");
return scan.nextLine();
}
}
}
TA贡献1809条经验 获得超8个赞
问题是当您使用系统关闭扫描仪时。来自系统的输入流也被关闭。因此,即使您使用 System.in 创建一个新的扫描仪,您也将无法重用该扫描仪。如果您使用的是 java 7,您可以使用 try 和资源来通过 Java 本身关闭所有 autocCleasable 资源。这将解决该问题。
public static void modifyContact(String namee) {
File file = new File("addressBook.txt");
try (Scanner sca = new Scanner(System.in);
Scanner sc = new Scanner(file);
FileWriter pw = new FileWriter(file, true);) {
String[] s;
boolean foundPerson = false;
String newName = sca.nextLine();
while (sc.hasNextLine()) {
s = sc.nextLine().split(",");
if (s[0].equals(namee)) {
s[0] = s[0].replace(s[0], newName);
System.out.println("Name is " + namee + " phone number is " + s[1] + " ,address is " + s[3]
+ " and email is " + s[2]);
foundPerson = true;
deleteByName(namee);
pw.write(s[0] + "," + s[1] + "," + s[2] + "," + s[3]);
}
}
if (!foundPerson) {
System.out.println("No contact found with " + namee);
}
} catch (IOException ex) {
// System.out.println(ex.getMessage());
}
}
添加回答
举报