[英]Java: BufferedWriter NullPointerException
我试图编写一个方法,必须接受一个Writer
对象,并使用它来提供文件的输出。 我当前的代码是抛出一个NullPointerException
,大概是因为我在创建BufferedWriter的过程中有错误,或者在某些情况下w
( Writer
对象)被传递为null
。 我无法控制作为w
传递的内容,并且无法更改此方法可以抛出的异常。
我的代码如下:
public void write(Writer w, Stat s) throws IOException {
try{
BufferedWriter writeFile = new BufferedWriter(w);
writeFile.write(s.getData());
writeFile.flush();
} catch (IOException e){
...
}
}
有什么我做错了吗?
(这项作业来自作业,但这个问题不是作业本身)
你需要Writer w
和Stat s
都不为null。 因此,如果它们为null,则应拒绝它们。
public void write(Writer w, Stat s) throws IOException {
if (w == null)
throw new IllegalArgumentException("writer is null");
if (s == null)
throw new IllegalArgumentException("stats is null");
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.