在android中的FileNotFoundException:/mimetype/mnt/sdcard/file.csv(没有这样的文件或目录)

时间:2013-01-02 05:41:57

标签: android file

我正在尝试读取位于SD卡中的csv文件,但是当我选择文件时,我得到的文件未找到异常。以下是我的代码。

Intent intent = new Intent();             //Browse the file
    intent.setType("file/csv");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select csv"),
            SELECT_CSV_Dialog);

 if (resultCode == RESULT_OK) {
 if (requestCode == 1) {
  data = result.getData();//data is the URI
 System.out.println("res "+data);
 if (data.getLastPathSegment().endsWith("csv") || data.getLastPathSegment().endsWith("CSV")) {       
     try {
         File f = new File(data.getPath());//this is where i get the file not found             
         FileInputStream  fis =new FileInputStream(f);   
            fis = this.openFileInput(data.toString());
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(fis));
                             String line;
            while ((line = reader.readLine()) != null) {
                String[] RowData = line.split(",");
                System.out.println("row  "+RowData.length);
                if(RowData.length==2){                      

        Toast.makeText(Importt.this, "Schema Supported", Toast.LENGTH_SHORT).show();
                    break;
                }else{
    Toast.makeText(Importt.this, "Schema not Supported", Toast.LENGTH_SHORT).show();
                }
            }}

这是我收到错误“File f = new File(data.getPath());”。

非常感谢任何建议。

3 个答案:

答案 0 :(得分:4)

使用以下代码从csv文件中读取数据。它对我有用。

try
   {
    List<String> list = new ArrayList<String>();
    String line;

    String fileName = "/mnt/sdcard/test.csv";
    FileReader reader = new FileReader(fileName);
    BufferedReader bufrdr = new BufferedReader(reader);
    line = bufrdr.readLine();
    while (line != null) {
        list.add(line);
        line = bufrdr.readLine();
    }
    bufrdr.close();
    reader.close();

    String[] array = new String[list.size()];
    list.toArray(array);

    for (int i = 0; i < list.size(); i++) {
        System.out.println(" 22222222 0 0 " + list.get(i).toString() );
    }

 }
  catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
}

对于SD-CARD检查,请使用以下行:

static public boolean hasStorage(boolean requireWriteAccess) {
    //TODO: After fix the bug,  add "if (VERBOSE)" before logging errors.
    String state = Environment.getExternalStorageState();
    Log.v(TAG, "storage state is " + state);

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (requireWriteAccess) {
            boolean writable = checkFsWritable();
            Log.v(TAG, "storage writable is " + writable);
            return writable;
        } else {
            return true;
        }
    } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

编辑2 使用以下代码从SD卡中提取文件。

private static final int FILE_SELECT_CODE = 0;

    private void showFileChooser() {
        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"),
                    FILE_SELECT_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();
        }
    }

然后你会在onActivityResult()中监听所选文件的Uri,如下所示:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:      
            if (resultCode == RESULT_OK) {  
                // Get the Uri of the selected file 
                Uri uri = data.getData();
                Log.d(TAG, "File Uri: " + uri.toString());
                // Get the path
                String path = FileUtils.getPath(this, uri);
                Log.d(TAG, "File Path: " + path);
                // Get the file instance
                // File file = new File(path);
                // Initiate the upload
            }           
            break;
        }
    super.onActivityResult(requestCode, resultCode, data);
    }


public static String getPath(Context context, Uri uri) throws URISyntaxException {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor
                .getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        }

    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

答案 1 :(得分:2)

试试这个,首先在SD卡中设置文件路径,它将解决您的问题。

File filePath = new File(Environment.getExternalStorageDirectory()+ "/filename.csv");

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = filePath.getName().substring(filePath.getName().indexOf(".") + 1);
mimtype = mime.getMimeTypeFromExtension(ext.toLowerCase()); //here mimtype is your after (.) file extenstion
intent.setDataAndType(Uri.fromFile(filePath), mimtype);
startActivity(intent);

答案 2 :(得分:0)

使用下面的代码......这可能对你有帮助..

if(filename.equalsIgnoreCase("your_csv_file_name"))
                {
                    reader = new CSVReader(new FileReader(Environment.getExternalStorageDirectory()+"/directory_name/"+your_csv_filename+".csv"));
                    try 
                    {
                        List<String[]> myEntries = reader.readAll();

                        Log.d("size","size of LIST======>"+myEntries.size());
                        if(myEntries.size()>0)
                        {
                            for(int i=0;i<myEntries.size();i++)
                            {
                                String arr[]=myEntries.get(i);
                                list11=new ArrayList<String>();
                                for(int k=0;k<arr.length;k++)
                                {
                                    list11.add(arr[k]);

                                    //Log.d("log is", "data size is==>"+arr[k]);
                                }

                            }
                        }
                    }
                    catch (Exception e) 
                    {
                        e.printStackTrace();
                    }
                }

注意: - 我使用opencsv.jar来读取和写入csv..so,请确保你的lib中有这个jar用于读取SD卡中的所有csv文件.. < / p>