如何删除FileNotFoundException:android中的异常?

时间:2014-10-20 07:55:15

标签: android

FilePath = / external / images / media / 2

获取错误: java.io.FileNotFoundException:/ external / images / media / 2(没有这样的文件或目录)

您好 我想在服务器上上传所选图像。我收到此错误 java.io.FileNotFoundException:/ external / images / media / 2(没有这样的文件或目录)。实际上我在模拟器上检查这个。首先我从图库中选择图像 然后获取所选图像的字节。但我找不到错误文件为什么

这是我的代码:

package com.CA.xmlparsing;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends Activity {

    private static final int PICKFILE_RESULT_CODE = 2;
    private String FilePath;

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

    public void upLoadImage(View view) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                PICKFILE_RESULT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }

    }  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Fix no activity available
        if (data == null)
            return;
        switch (requestCode) {
        case PICKFILE_RESULT_CODE:
            if (resultCode == RESULT_OK) {
                 FilePath = data.getData().getPath();
                //FilePath is your file as a string
                Log.d("--------------", FilePath);
// print /external/images/media/2
                byte[] bytes=  getFileByte(FilePath);
                Log.d("--------------", ""+bytes);
            }
        }
    }

  private   byte [] getFileByte(String path){
         File file = new File(path);
            int size = (int) file.length();
            byte[] bytes = new byte[size];
            try {
// getting error on this line
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
                buf.read(bytes, 0, bytes.length);
                buf.close();
            } catch (FileNotFoundException e) {
//catch here the error
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return bytes;
    }
}


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.CA.xmlparsing.MainActivity" >

 <Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="uploadImage"
     android:onClick="upLoadImage" />

</RelativeLayout>

是否有任何权限要求thar从模拟器中读取图像?

3 个答案:

答案 0 :(得分:1)

您获得的不是文件系统的文件路径,而是mediastore和其他人使用的媒体路径。为了获得真正的文件路径,您必须在媒体商店上调用游标。您可以在此站点上找到许多示例代码。

答案 1 :(得分:1)

您真正的问题是将图像转换为字节,以便您可以上传到服务器。 onActivityResult方法将为您提供Bitmap对象。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap bmp = (Bitmap) data.getExtras().get("data"); 
    }  
}

现在不是获取路径,而是将其转换为文件,然后再将其转换为字节,您可以直接使用位图您从onActivityResult方法获得的对象,并使用以下方法将其转换为字节。

public byte[] bitmapToByte(Bitmap bitmap){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

但这篇文章要求&#34;如何删除FileNotFoundException:android中的异常?&#34;,以便获取您需要的图像路径:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 

        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);

        // CALL THIS METHOD TO GET THE ACTUAL PATH
        File finalFile = new File(getAbsolutePathFromURI(tempUri));
    }  
}

public Uri getImageUri(Context context, Bitmap bitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(context.getContentResolver(), bitmap, "TempImage", null);
    return Uri.parse(path);
}

public String getAbsolutePathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(index); 
}

答案 2 :(得分:0)

您需要添加到Android清单中的权限,尽管这可能不是您唯一的问题。添加:

<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...