我试图编写一个必须接受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){
...
}
}我做错什么了吗?
(这个作业源于家庭作业,但这个问题并不是作业本身)
发布于 2015-10-05 19:00:00
您需要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");
...https://stackoverflow.com/questions/32955827
复制相似问题