且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将FileWriter作为参数传递给方法

更新时间:2022-06-27 02:40:38

您会遇到经典错误,忘记了在Java中按值传递的参数是引用的值.事情是你的任务

you make classic error forgetting that parameters passed by value in case of java it is a value of the reference. The thing is that your assignment

out = new BufferedWriter(new FileWriter(response));

实际上不会更改main()中声明的变量,而是保持为空

actually does not change the variable declared in main() it stays null

BufferedWriter out = null; 然后最后它会通过if(out == null)跳过close() 因为它是缓冲的,所以您不执行刷新操作,不会将任何内容写入文件. 您要做的是out.close();在FileOrConsole方法调用旁边

BufferedWriter out = null; and then in finally it skips the close() by the if(out==null) and as it is Buffered and you do no flush nothing is written to file. what you got to do is out.close(); in side the FileOrConsole method call

OR

执行out = new BufferedWriter(new FileWriter(response)); 在它外面.您选择:-)

do the out = new BufferedWriter(new FileWriter(response)); outside of it. You choose :-)