마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

filechooser로 선택한 Text File의 절대경로 얻기..

0 추천
@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();
            importFile = new File(uri.getPath());
            String sFilePath = importFile.getAbsolutePath();
            if (uri.getPath() != null) {
               edImportPath.setText(uri.getPath());
            }

            Log.d("File uri", "File Uri: " + uri.toString());
            // Get the path
            try {
               String path = getPath(this, uri);
               Log.d("File Path", "File Path: " + path);
               // Get the file instance
               // File file = new File(path);
               // Initiate the upload
            } catch (URISyntaxException use) {
               use.printStackTrace();
            }
         }
         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;
}

 

uri.getPath() = /document/primary:SiHAS/CfgFile/SiHAS_Setting_SHINA_LAB.txt

uri.toString() = content://com.android.externalstorage.documents/document/primary%3ASiHAS%2FCfgFile%2FSiHAS_Setting_SHINA_LAB.txt

getPath(this, uri) = null

절대경로값이 아니게 나오는데

절대경로를 어떻게 하면 얻을 수 있을까요?

zenojm (2,840 포인트) 님이 2017년 7월 12일 질문

1개의 답변

0 추천
 
채택된 답변
content:// URI에서 절대경로를 얻는 공식적인 방법은 없습니다.
익명사용자 님이 2017년 7월 12일 답변
zenojm님이 2017년 7월 13일 채택됨
그러면 filechooser로 선택한 텍스트 파일을 FileReader 로 읽을건데 파일 경로를 절대경로 말고 다른 방법으로 넣어서 사용할 수 있나요?
파일 내용을 읽는 것이 목적이면 아래함수를 사용하면 됩니다.
https://developer.android.com/reference/android/content/ContentResolver.html#openInputStream(android.net.Uri)
감사합니다 openInputStream 으로 해결했습니다. 너무너무감사합니다!!
...