IT박스

자산 파일에서 URI를 얻는 방법?

itboxs 2020. 7. 30. 10:14
반응형

자산 파일에서 URI를 얻는 방법?


자산 파일의 URI 경로를 얻으려고했습니다.

uri = Uri.fromFile(new File("//assets/mydemo.txt"));

파일이 존재하는지 확인하면 파일이 존재하지 않는 것을 볼 수 있습니다

File f = new File(filepath);
if (f.exists() == true) {
    Log.e(TAG, "Valid :" + filepath);
} else {
    Log.e(TAG, "InValid :" + filepath);
}

자산 폴더에 존재하는 파일의 절대 경로를 언급하는 방법을 알려줄 수 있습니까?


"자산 폴더에 존재하는 파일의 절대 경로"는 없습니다. 프로젝트 assets/폴더 의 내용은 APK 파일로 패키지됩니다. AssetManager개체를 사용하여 InputStream자산 을 가져옵니다 .

의 경우 URL을 사용하는 것과 거의 같은 방식으로 체계를 WebView사용할 수 있습니다 file Uri. 자산의 구문은 file:///android_asset/...(주 : 슬래시 3 개)입니다. 여기서 줄임표는 assets/폴더 내에서 파일의 경로입니다 .


올바른 URL은 다음과 같습니다.

file:///android_asset/RELATIVEPATH

여기서 RELATIVEPATH는 자산 폴더와 관련된 리소스의 경로입니다.

구성표의 3 /에 유의 하십시오. 웹보기는 3이 없으면 내 자산을로드하지 않습니다. CommonsWare가 (이전) 주석으로 2를 시도했지만 작동하지 않습니다. 그런 다음 github에서 CommonsWare의 소스를보고 추가 슬래시를 발견했습니다.

이 테스트는 1.6 Android 에뮬레이터에서만 수행되었지만 실제 장치 또는 상위 버전에서는 다른 것으로 의심됩니다.

편집 : CommonsWare는이 작은 변화를 반영하기 위해 그의 대답을 업데이트했습니다. 그래서 나는 이것을 편집하여 현재의 대답에 여전히 합리적입니다.


여기에 이미지 설명을 입력하십시오

자산 폴더가 올바른 위치에 있는지 확인하십시오.


이 코드가 제대로 작동하는지 확인하십시오

 Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));

    /* 2) Create a new Intent */
    Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
            .setData(imageUri)
            .build();

WebView에서 작동하지만 실패한 것 같습니다 URL.openStream(). 따라서 file : // 프로토콜을 구별하고 제안 된대로 AssetManager를 통해 처리해야합니다.


InputStream is = getResources().getAssets().open("terms.txt");
    String textfile = convertStreamToString(is);

public static String convertStreamToString(InputStream is)
            throws IOException {
            Writer writer = new StringWriter();

            char[] buffer = new char[2048];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is,
                        "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            String text = writer.toString();
            return text;

이것을 시도하십시오 : 그것은 작동합니다

InputStream in_s = getClass().getClassLoader().getResourceAsStream("TopBrands.xml");

null 값 예외가있는 경우 다음 중 하나를 시도하십시오.

InputStream in_s1 =   TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");

TopBranData는 클래스입니다


마지막으로 Kotlin 의이 답변에서 자산에 존재하는 파일의 경로를 얻는 방법을 찾았습니다 . 여기서 자산 파일을 캐시에 복사하고 해당 캐시 파일에서 파일 경로를 가져옵니다.

@Throws(IOException::class)
fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
    .also {
        it.outputStream().use { cache -> context.assets.open(fileName).use { it.copyTo(cache) } }
    }

다음과 같이 파일 경로를 가져옵니다.

val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath

이 시도 :

Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat); 

나는 그것을했고 효과가 있었다.


컴퓨터와 안드로이드는 서로 다른 OS이기 때문에 안드로이드 폰이나 에뮬레이터에서 드라이브 폴더에 액세스 할 수 없습니다. 좋은 리소스 관리 방법이 있기 때문에 안드로이드 폴더로 갈 것입니다. 자산 폴더에 파일을 넣을 이유가 충분하지 않을 때까지. 대신 당신은 이것을 할 수 있습니다

try {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.yourfile);

      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String str = new String(b);
    } catch (Exception e) {
      Log.e(LOG_TAG, "File Reading Error", e);
 }

나를 위해 일했다이 코드를 사용해보십시오

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
 }

참고 URL : https://stackoverflow.com/questions/4820816/how-to-get-uri-from-an-asset-file

반응형