我正在尝试通过WiFi将视频文件从RPi热点传输到手机上的目录中。我已经能够在存储中成功创建一个文件夹,与RPi服务器连接并接收数据。但是,写入后出现的文件不正确。实际上,当我尝试打开它时,它只是在手机上打开了一个单独的,不相关的应用程序。很奇怪!

这是有问题的代码:

 try {
            BufferedInputStream myBis = new BufferedInputStream(mySocket.getInputStream());
            DataInputStream myDis = new DataInputStream(myBis);

            byte[] videoBuffer = new byte[4096*2];
            int i = 0;

            while (mySocket.getInputStream().read(videoBuffer) != -1) {
                Log.d(debugStr, "while loop");
                videoBuffer[videoBuffer.length-1-i] = myDis.readByte();
                Log.d(debugStr, Arrays.toString(videoBuffer));
                i++;
            }

            Log.d(debugStr, "done with while loop");
            // create a File object for the parent directory

            File testDirectory = new File(Environment.getExternalStorageDirectory()+File.separator, "recordFolder");
            Log.d(debugStr, "path made?");
            if(!testDirectory.exists()){
                testDirectory.mkdirs();
            }
            Log.d(debugStr, "directory made");
            // create a File object for the output file
            File outputFile = new File(testDirectory.getPath(), "recording1");

            Log.d(debugStr, "outputfile made");
            // now attach the OutputStream to the file object, i

            FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
            Log.d(debugStr, "write to file object made");


            fileOutputStream.write(videoBuffer);
            Log.d(debugStr, "video written");
            fileOutputStream.close();

            Log.d(debugStr, "done");
        } catch (IOException e1) {
            e1.printStackTrace();
        }


该视频最初为.h264格式,并作为字节数组发送。该文件的大小为10MB。在我的while循环中,我将数组的值作为字符串打印出来,并且它打印了大量数据。足够的数据让我怀疑所有数据都已发送。当我导航到该文件夹​​时,应该有一个名为“ recording1”的文件,但大小只有8KB。

有什么想法吗?任何帮助是极大的赞赏!

最佳答案

Android FileOutputStream似乎失败


不,不是。您的代码似乎失败。那是因为您的代码没有意义。您正在丢弃大量数据,或多或少地每8192个字节中仅累积1个;您同时使用了缓冲读取和非缓冲读取;您将输入限制为8192字节;而且您永远都不会关闭输入。如果输入大于8192 * 8193,则可以得到ArrayIndexOutOfBoundsException

将其全部扔掉并使用:

try {
        File testDirectory = new File(Environment.getExternalStorageDirectory()+File.separator, "recordFolder");
        if(!testDirectory.exists()){
            testDirectory.mkdirs();
        }
        File outputFile = new File(testDirectory, "recording1");
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
            BufferedInputStream in = new BufferedInputStream(mySocket.getInputStream())) {
            byte[] buffer = new byte[8192]; // or more, whatever you like > 0
            int count;
            // Canonical Java copy loop
            while ((count = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, count);
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

09-06 08:39