62,628
社区成员
发帖
与我相关
我的任务
分享
能看明白吗,你firstFosWrite方法的形参fos其实是重新在栈上开了一个引用(存储于虚拟机栈,线程安全的),两个开始都是null,然后你对后面一个赋值了,之前那个还是null,向下面这种最简单的代码,你试一下看看
public static void main(String[] args) {
int i =7;
System.out.println(i);
}
public static void tt(int i) {
i = 9;
}
改成这样就可以了
if (writeNum == 1) { // 第一次接收
fos = new FileOutputStream(file);
firstFosWrite(file, byte[], fos);
}else{
fosWrite(byte[], fos);
}
多线程情况下直接到方法里去初始化,刚才也说过了,方法里的局部变量表是线程安全的,不需要两个方法,就一个方法就行了
private void fosWrite(File file, byte[] bytes) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
}