Đọc file và ghi file vào bộ nhớ internal Android từ thư mục raw

5/5 - (1 vote)

Có thể hiểu đây làm snippet tiện, nhanh, gọn để test khi bạn phát triển ứng dụng Android bằng Java:

Ghi toàn bộ file

InputStream fileInputStream = getResources().openRawResource(getResources().getIdentifier("sample_ocean_with_audio", "raw", getPackageName()));
            try {
                FileOutputStream outputStream = new FileOutputStream(Tool.getAppRootPath() + "/abc.mp4");
                byte[] localBuffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = fileInputStream.read(localBuffer)) != -1) {
                    outputStream.write(localBuffer);
                    LogI("writing......");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

Ghi khoảng 1/2 kích thước file gốc

InputStream fileInputStream = getResources().openRawResource(getResources().getIdentifier("sample_ocean_with_audio", "raw", getPackageName()));
            try {
                int size = fileInputStream.available()/2;
                FileOutputStream outputStream = new FileOutputStream(Tool.getAppRootPath() + "/abc.mp4");
                byte[] localBuffer = new byte[1024];
                int totalBytesRead = 0;
                int bytesRead = 0;
                while ((bytesRead = fileInputStream.read(localBuffer)) != -1) {
                    if (totalBytesRead >= size) {
                        LogI("exitttttttttttt");
                        break;
                    }
                    totalBytesRead += bytesRead;
                    outputStream.write(localBuffer);
                    LogI("writing......");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

Hàm getAppRootPath:

  public static String getAppRootPath() {
        PackageManager pM = getPackageManager();
        String root_folder = getPackageName();
        PackageInfo pI = null;
        try {
            pI = pM.getPackageInfo(root_folder, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        root_folder = pI.applicationInfo.dataDir;
        return root_folder;
    }

Tham khảo thêm:

https://dotrinh.com/hieu-ve-cach-to-chuc-file-trong-android/

*Bài viết này sẽ được bổ sung thêm.

Các bài viết không xem thì tiếc:

Thảo luận

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
 
 
 
Facetime iPhone

Main Menu