为了实现这一点,您需要在运行时刷新输出流。
public class TempFile2 {
private File file;
private File tempFile;
private FileOutputStream os;
public TempFile2(File file) {
this.file = file;
this.tempFile = new File(file.getParent(), FilenameUtils.getBaseName(file.getName()) + ".tmp");
if (!tempFile.exists()) {
try {
tempFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void addEntry(byte[] data, int count) {
try {
os.write(data, 0, count);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
try {
os.close();
Files.copy(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
事实上,您可以在每次收到数据块时打开和关闭输出流,而不是保持输出流打开:
public class TempFile2 {
private File file;
private File tempFile;
public TempFile2(File file) {
this.file = file;
this.tempFile = new File(file.getParent(), FilenameUtils.getBaseName(file.getName()) + ".tmp");
if (!tempFile.exists()) {
try {
tempFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void addEntry(byte[] data, int count) {
try(OutputStream os = new FileOutputStream(tempFile, true)) {
os.write(data, 0, count);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
try {
Files.copy(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
另外,我有一个建议。
read()操作可能只读取几个字节,但您当前的实现无论如何都会发送整个数组。对此的一个解决方案是制作一个新的更小的阵列来保存数据:
byte[] bytesToSend = new byte[count];
System.arraycopy(buf, 0, bytesToSend, 0, count);
我认为一个更好的解决方案是在这里使用Base64类,发送字节数组的序列化版本,而不是字节数组本身。
// In sender
byte[] bytesToSend = new byte[count];
System.arraycopy(buf, 0, bytesToSend, 0, count);
String encodedBytes = Base64.getEncoder().encodeToString(bytesToSend);
msg.setValue(MType.FILE_BYTE, encodedBytes);
// In receiver
String encodedBytes = (String) msg.getValue(MType.FILE_BYTE);
buf = Base64.getDecoder().decode(encodedBytes);