0

I am trying to read csv file which is located in SD card but when i select the file i get a File not found Exception.The below is my code.

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

This is where i get the error "File f = new File(data.getPath());".

Any suggestions are highly appreciated.

4

3 回答 3

4

Use the below code to read the data from csv file . it worked for me .

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

For SD-CARD Checking use the following lines :

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

EDIT 2 use the below code to bring the file from sdcard.

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

You would then listen for the selected file's Uri in onActivityResult() like so:

@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;
}
于 2013-01-02T05:56:19.453 回答
2

Try this, first set your file path in sdcard, it will solve your problem.

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);
于 2013-01-02T06:04:48.243 回答
0

use below code...this might help you..

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

Note:-here i am using opencsv.jar for read and write csv..so, be make sure you have this jar in your lib for read all csv file from sd card..

于 2013-01-02T06:21:54.853 回答