我尝试将我从套接字接收到的数据写入一个文件,我将数据存储在一个数组中,但是当我写入它们时,文件变得太大了...... 我认为这是由使用大数组引起的,因为我不知道数据流的长度...
但是检查 write 方法表明 write(byte[] b) 将指定字节数组中的 b.length 字节写入此文件输出流, write() 方法读取数组的长度,但长度是 2000... 我如何知道将要写入的数据的长度?
...
byte[] Rbuffer = new byte[2000];
dis = new DataInputStream(socket.getInputStream());
dis.read(Rbuffer);
writeSDCard.writeToSDFile(Rbuffer);
...
void writeToSDFile(byte[] inputMsg){
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/download");
if (!(dir.exists())) {
dir.mkdirs();
}
Log.d("WriteSDCard", "Start writing");
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file, true);
f.write(inputMsg);
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
read()
返回读取的字节数,或 -1。您忽略了这两种可能性,和 假设它填满了缓冲区。您所要做的就是将结果存储在一个变量中,检查是否为 -1,否则将其传递给 write()
方法。
实际上你应该将输入流传递给你的方法,并在创建文件后使用循环:
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
您在现已删除的评论中关于为每个数据包创建一个新输入流的声明是不正确的。
关于java - 使用 write() 方法,文件变得太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806138/