【发布时间】:2017-02-24 09:27:45
【问题描述】:
下面的代码从HTTP请求中获取一个字节数组并保存在bytes[]中,最终的数据会保存在message[]中。
我通过将其转换为 String[] 来检查它是否包含标头,如果有,我会从标头中读取一些信息,然后通过将标头后面的字节保存到 message[] 来将其切断。
然后我尝试使用 FileOutputStream 将 message[] 输出到文件,它工作得稍微好一点,但只保存了 10KB 的信息,while 循环的一次迭代,(似乎被覆盖),如果我设置 FileOutputStream(file, true) 附加信息,它可以工作......一次,然后文件只是添加到我下次运行它时,这不是我想要的。如何在每次迭代中使用多个字节块写入同一个文件,但如果再次运行程序,仍然会完整地覆盖文件?
byte bytes[] = new byte[(10*1024)];
while (dis.read(bytes) > 0)
{
//Set all the bytes to the message
byte message[] = bytes;
String string = new String(bytes, "UTF-8");
//Does bytes contain header?
if (string.contains("\r\n\r\n")){
String theByteString[] = string.split("\r\n\r\n");
String theHeader = theByteString[0];
String[] lmTemp = theHeader.split("Last-Modified: ");
String[] lm = lmTemp[1].split("\r\n");
String lastModified = lm[0];
//Cut off the header and save the rest of the data after it
message = theByteString[1].getBytes("UTF-8");
//cache
hm.put(url, lastModified);
}
//Output message[] to file.
File f = new File(hostName + path);
f.getParentFile().mkdirs();
f.createNewFile();
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(message);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
【问题讨论】:
标签: java arrays fileoutputstream