【问题标题】:using write() method, the file gets too big使用 write() 方法,文件变得太大
【发布时间】:2017-02-09 21:28:32
【问题描述】:

我尝试写入一个文件,我从套接字接收的数据,我将数据存储在一个数组中,但是当我写入它们时,文件变得太大了...... 我认为这是由于使用了大数组引起的,因为我不知道数据流的长度...

但是检查方法 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();
    }
}

【问题讨论】:

  • 不是一次读取整个文件,您可以在下载时编写它,然后不管它如何。从 InputStream 中读取一点并将其复制到 OutputStream 中,例如每次 512 字节到 8 KB。
  • @peter-lawrey 我怎样才能在不丢失流的情况下只读取几位...因为另一个流将会到来(同时...)
  • 阅读read 方法的文档。它有一个有用的返回值

标签: java android arrays fileoutputstream


【解决方案1】:

read() 返回已读取的字节数,或 -1。您忽略了两种可能性, 假设它已填满缓冲区。您所要做的就是将结果存储在一个变量中,检查是否为 -1,否则将其传递给 write() 方法。

实际上你应该将输入流传递给你的方法,并在创建文件后使用循环:

int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

您在现已删除的评论中关于每个数据包创建一个新输入流的说法不正确。

【讨论】:

  • 为了将它传递给 write 方法,我必须插入和偏移量(我认为它将是 0),因为我希望将所有输​​入流插入到文件中......但是在收到一些负长度的消息后,这是什么意思,(传输完成了吗?)
  • 是的。我确实提到了-1。您是否考虑过查阅 Javadoc?
  • 刚刚意识到,文件对于存储来说不是太大,文件比它应该的大。考虑到文件的预期大小,可能会尝试使用 2048 字节的缓冲区。 +1
猜你喜欢
  • 2022-06-30
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 2019-04-14
  • 2015-12-06
相关资源
最近更新 更多