【发布时间】:2016-12-12 22:48:02
【问题描述】:
我有一个简单的“家庭作业”要做,但我发现输入流的关闭有一点问题。 简而言之,我必须在 Java 中创建一个联系人“列表”应用程序,以便以正确的方式使用多态性。所以我有一个类 Contact 和一个子类 Private(联系人)。在这两个类中都有一个修改方法来更改变量的值。
public void modify() throws IOException {
System.out.println("Previously name: " + name);
System.out.println("Insert new name");
try(InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(ir) ) {
name= in.readLine();
System.out.println("You've changed the name to: "+ name);
System.out.println("Previously surname: " + surname);
System.out.println("Insert new surname");
surname= in.readLine();
System.out.println("You've changed the surname to: "+ surname);
System.out.println("Previously e-mail: " + email);
System.out.println("Insert new e-mail");
email = in.readLine();
System.out.println("You've changed the e-mail to: "+ email); }
}
这是不会产生问题的 Contact 方法
@Override
public void modify() throws IOException {
super.modifica();
System.out.println("Numero di cellulare precedente: " + cell);
System.out.println("Inserire nuovo numero");
try (InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(ir)) {
cell = in.readLine();
System.out.println("Hai cambiato il numero in: "+ cell);
System.out.println("Contatto skype precedente: " + skype);
System.out.println("Inserire nuovo contatto");
skype = in.readLine();
System.out.println("Hai cambiato il contatto in: "+ skype);
}
}
相反,这是 Private 中方法的覆盖。 主要是创建一个 Private 对象并调用 modify 方法。我可以毫无问题地插入姓名、姓氏和电子邮件,然后该方法由于流已关闭而引发 IO 异常。 我不明白为什么我会遇到这种问题。我认为在第一个代码中尝试使用资源关闭了流,但随后在第二个代码中通过另一个尝试使用资源打开了它。可能我的想法有问题。
【问题讨论】:
-
也许你应该了解一下
java.util.Scanner。你可以从这里开始:*.com/a/11871792/4791599 -
谢谢! Scanner 和 BufferedReader 在内存的潜力和管理方面是否存在差异?
标签: java stream overriding try-with-resources