Android FileOutputStream似乎失败了

时间:2017-03-13 03:20:01

标签: java android file sockets

我正在尝试通过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。

有关正在发生的事情的任何想法?任何帮助是极大的赞赏!

1 个答案:

答案 0 :(得分:2)

  

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();
    }