[英]Java: BufferedWriter NullPointerException
I am attempting to write a method that has to take in a Writer
object and use that to provide output to a file. 我试图编写一个方法,必须接受一个
Writer
对象,并使用它来提供文件的输出。 The current code I have is throwing a NullPointerException
, presumably because either there is an error in how I am creating my BufferedWriter or else in some instances w
(the Writer
object) is being passed as null
. 我当前的代码是抛出一个
NullPointerException
,大概是因为我在创建BufferedWriter的过程中有错误,或者在某些情况下w
( Writer
对象)被传递为null
。 I have no control over what is passed as w
, and cannot change the exceptions that this method is able to throw. 我无法控制作为
w
传递的内容,并且无法更改此方法可以抛出的异常。
My code is as follows: 我的代码如下:
public void write(Writer w, Stat s) throws IOException {
try{
BufferedWriter writeFile = new BufferedWriter(w);
writeFile.write(s.getData());
writeFile.flush();
} catch (IOException e){
...
}
}
Is there something I'm doing wrong? 有什么我做错了吗?
(This assignment arises out of homework, but this question isn't the homework itself) (这项作业来自作业,但这个问题不是作业本身)
You need both Writer w
and Stat s
to be not null. 你需要
Writer w
和Stat s
都不为null。 Therefore you should reject them if they are 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.