FileUtils.readFileToByteArray(new File(FilePath))在android中显示FileNotFoundException

时间:2014-12-01 14:45:25

标签: android

我想使用IntentService上传视频/mfs_candidate_intro/65850.mp4

文件结构就是这样..

MainActivity.java

package com.servicedemo;

import java.io.File;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {


    private String fpath;
    private String myfile;
    private static final String UPLOAD_URL = "http://www.ourgoalplan.com/CandidateIntroUploader.ashx";
    private int candidateID =65850; 


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


   public void startMethod(View v) {

       fpath=setVideoOutPutFile();
       Log.e("Inside",fpath);
       Toast.makeText(getApplicationContext(), fpath, Toast.LENGTH_LONG).show();
        Intent i=new Intent(MainActivity.this,Uploadservice.class);
        i.putExtra("filepath", fpath);
        i.putExtra("uploadurl", UPLOAD_URL);
        i.putExtra("candidateID", candidateID);
        startService(i);
}



   private String setVideoOutPutFile()
    {
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "/mfs_candidate_intro");
        if (!mediaStorageDir.exists())
        {
            if (!mediaStorageDir.mkdirs())
            {
                Log.d("VideoLogger", "failed to create directory");
            }
        }

        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        myfile = path + "/mfs_candidate_intro/" + candidateID + ".mp4";

        return myfile;
    }



}

Uploadservice.java

package com.servicedemo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.FileUtils;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class Uploadservice extends IntentService{

    private String uploadURL;
    private int candidateID;
    private String FilePath;

    public Uploadservice() {      
        super("My service");

    }

    @Override
    public IBinder onBind(Intent intent) {
    return null;
    }



    @Override
    protected void onHandleIntent(Intent intent) {   //After completion of onstartcommand system will deliver all intent object to onHandleItent method.          

        uploadURL=intent.getExtras().getString("uploadurl");
        candidateID=intent.getExtras().getInt("candidateID");
        FilePath =intent.getExtras().getString("filepath");
        Log.d("Inside onhandleIntent", FilePath);
        try {
            uploadVideo(uploadURL,candidateID,FilePath);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }



    public void uploadVideo(String iUploadUrl, int iCandidateId, String iFilePath) throws IOException
    {
        /**
         * converts the file in the specified path to byte Array
         */
        byte[] videobytes = convertFileToBytes(iFilePath);
        // Number of chunks in Bytes..
        final long chunkSize = 100000;
        // creates a new file in the specified path..
        File videoFile = new File(iFilePath);
        if (videobytes != null && videobytes.length > 0)
        {
            String requestUri = iUploadUrl + "?CandidateID=" + iCandidateId + "&fileName=" + videoFile.getName();

            // get the number of chunks
            long numOfChunks = (videobytes.length / chunkSize);
            byte[] byteArray = new byte[(int) chunkSize];

            /**
             * Get the remaining Bytes. /Check if there is some bytes remaining after calculation of numOfChunks
             */
            long remaingbytes = videobytes.length % chunkSize;
            if (remaingbytes > 0)
            {
                // Increase number of chunks by one if some bytes are left ...
                numOfChunks = numOfChunks + 1;
            }
            long copyBytesLength = chunkSize;

            for (int chunkNo = 1; chunkNo <= numOfChunks; chunkNo++)
            {
                String requestURL = requestUri + "&TotalChunks=" + numOfChunks + "&ChunkCounter=" + chunkNo;
                copyBytesLength = ((chunkNo * chunkSize) > videobytes.length) ? remaingbytes : chunkSize;
                byteArray = new byte[(int) copyBytesLength];
                System.arraycopy(videobytes, (int) ((chunkNo - 1) * chunkSize), byteArray, 0, (int) copyBytesLength);

                // send request to Handler
                if (requestHandler(numOfChunks, byteArray, chunkNo, requestURL))
                {
                    Log.e("SplashScreen", "Request Handler Returns False " + iCandidateId);
                    break;
                }
            }

        }
    }

    /**
     * This method provides the file data as byte array
     * 
     * @param iFilePath
     *            the path to the file
     * @return the corresponding byte array representation
     * @throws IOException
     */
    private byte[] convertFileToBytes(String iFilePath) throws IOException
    {
        return FileUtils.readFileToByteArray(new File(iFilePath));
    }

    /**
     * This method handles the division of byte array data into small chunks
     * 
     * @param iNumOfChunks
     *            number of chunks available after dividing data as separate 1 MB units
     * @param iByteArray
     *            the byte array representation of video data.
     * @param iChunkNum
     *            current chunk number
     * @param iRequestURL
     *            complete upload url
     * @return true/false based upon the success result.
     */
    private boolean requestHandler(long iNumOfChunks, byte[] iByteArray, int iChunkNum, String iRequestURL)
    {
        try
        {
            boolean valid = true;
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            DataInputStream inStream = null;
            URL url = new URL(iRequestURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            dos = new DataOutputStream(conn.getOutputStream());
            // Writes iByteArray.length from IByteArray starting at offset 0 to the dos output stream.
            dos.write(iByteArray, 0, iByteArray.length);
            dos.flush();
            dos.close();
            // get the response code returned by the HTTP server...
            int responseCode = conn.getResponseCode();
            Log.e("SplashScreen", "Response code is " + responseCode);
            /**
             * If response code is OK ,Check if the iChunkNum == iNumOfChunks If it is equal ,it means Writting to th
             */
            if (responseCode == HttpURLConnection.HTTP_OK)
            {
                if (iChunkNum == iNumOfChunks)
                {
                    inStream = new DataInputStream(conn.getInputStream());
                    String str;
                    StringBuffer buf = new StringBuffer();
                    while ((str = inStream.readLine()) != null)
                    {
                        buf.append(str);
                    }
                    str = buf.toString();
                    Log.e("SplashScreen", "Server Response" + str);
                    inStream.close();
                }
                else
                {
                    valid = false;
                }
            }
            return valid;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }

    }

 @Override
public void onDestroy() {
    Log.d("destroyed", "Intent destroyed");
    Toast.makeText(getApplicationContext(), "helloooooooooooo", Toast.LENGTH_LONG).show();
    super.onDestroy();
}

}

在activity_main.xml里面有一个按钮,在点击时调用startMethod(View v)。

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.servicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

         <service
             android:name=".Myservice"
             android:exported="false"
        />

         <service
             android:name=".Uploadservice"
             android:exported="false"
        />

    </application>



</manifest>

我的问题是显示以下异常

12-01 14:34:00.179: W/System.err(3676): java.io.FileNotFoundException: File '/storage/emulated/0/mfs_candidate_intro/65850.mp4' does not exist
12-01 14:34:00.179: W/System.err(3676):     at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:299)
12-01 14:34:00.183: W/System.err(3676):     at org.apache.commons.io.FileUtils.readFileToByteArray(FileUtils.java:1763)
12-01 14:34:00.183: W/System.err(3676):     at com.servicedemo.Uploadservice.convertFileToBytes(Uploadservice.java:112)
12-01 14:34:00.183: W/System.err(3676):     at com.servicedemo.Uploadservice.uploadVideo(Uploadservice.java:60)
12-01 14:34:00.183: W/System.err(3676):     at com.servicedemo.Uploadservice.onHandleIntent(Uploadservice.java:44)
12-01 14:34:00.183: W/System.err(3676):     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
12-01 14:34:00.183: W/System.err(3676):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-01 14:34:00.183: W/System.err(3676):     at android.os.Looper.loop(Looper.java:136)
12-01 14:34:00.183: W/System.err(3676):     at android.os.HandlerThread.run(HandlerThread.java:61)

当我在移动设备上运行时,也会显示OutOfMemory异常。

还有一件事..在mfs_candidate_intro文件夹里面有65850.mp4视频(在文件管理器里面)

请帮助......我已经搜索了很多解决方案,但无法找到...... 在此先感谢.. :))

1 个答案:

答案 0 :(得分:1)

您是否需要在清单中设置权限以读取/写入您的SD卡? :S

Android Developer - READ EXTERNAL STORAGE