2017-06-06 13 views
0

我試圖從Google驅動器中加載CSV文件並使用java解析它。但是,無論何時我選擇該文件,它都會顯示例外情況:未找到文件Android-從Google Drive中選擇CSV文件並使用java解析它

下面是我實現的代碼:

選配意向代碼:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("text/csv"); //XML file only 
    intent.addCategory(Intent.CATEGORY_OPENABLE); 
    try 
    { 
     startActivityForResult(Intent.createChooser(intent, "Select"), 100); 
    } catch (android.content.ActivityNotFoundException ex) 
    { 
     // Potentially direct the user to the Market with a Dialog 
     Toast.makeText(this, "Drive Not Found", Toast.LENGTH_SHORT).show(); 
    } 

onActivity結果:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) 
    { 
     case 100: 
      { 
      if (resultCode == RESULT_OK) 
      { 
       //onImport(new File(data.getData().getPath())); 
       String filePath = null; 
       Uri uri = data.getData(); 

       File file = new File(uri.toString()); 
       if (file.exists()) { 
        //Do something 
        System.out.println("Exists"); 
        proImportCSV(new File(data.getData().getPath())); 
       } 
       else 
       { 
        System.out.println("Not Exists"); 
       } 

      } 
     } 
    } 
} 

CSV解析使用CSVReader

private void proImportCSV(File from) 
{ 
    try 
    { 
     // reading CSV and writing table 
     CSVReader reader = null; 
     try 
     { 
      reader = new CSVReader(new FileReader(from)); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
     String[] nextLine; 
     try { 
      while ((nextLine = reader.readNext()) != null) { 
       // nextLine[] is an array of values from the line 
       System.out.println(nextLine[0] + nextLine[1] + "etc..."); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

請告訴我爲什麼我找不到文件找不到錯誤。另外,我是否正確解析csv?如果不對,請告訴我有關細節的正確答案。

在此先感謝!

回答

0

我已經使用bufferReader解析了它,一切都變得完美了!

 Uri uri = data.getData();  
      BufferedReader mBufferedReader = null; 
      String line; 

      try 
       { 
        InputStream inputStream = getContentResolver().openInputStream(uri); 
        mBufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
        while ((line = mBufferedReader.readLine()) != null) 
        { 
         System.out.println("LLLLL: "+ line); 
        } 
        mBufferedReader.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       }