'एसेट' फोल्डर से sdcard में फाइल कॉपी कैसे करें?


250

मेरे पास assetsफ़ोल्डर में कुछ फाइलें हैं । मुझे उन सभी को एक फ़ोल्डर कहने / sdcard / फ़ोल्डर में कॉपी करने की आवश्यकता है। मैं इसे एक सूत्र के भीतर से करना चाहता हूं। मैं यह कैसे करुं?


आप इस के लिए देख रहे stackoverflow.com/questions/4447477/...
DropAndTrap

2
इससे पहले कि आप नीचे दिए गए (महान!) समाधानों में से एक को कॉपी / पेस्ट करें, इस लाइब्रेरी का उपयोग कोड की एक पंक्ति में करने के लिए विचार करें: stackoverflow.com/a/41970539/9648
जॉनी लैम्बडा

जवाबों:


345

अगर किसी और को भी यही समस्या हो रही है, तो मैंने यही किया

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          out = new FileOutputStream(outFile);
          copyFile(in, out);
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }     
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
        }  
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

संदर्भ: जावा का उपयोग करके फ़ाइल को स्थानांतरित करें


28
sdcard में फाइलें लिखने के लिए आपको मैनिफ़ेस्ट पर अनुमति देनी होगी। उदाहरण के लिए <उपयोग-अनुमति एंड्रॉइड: नाम = "android.permission.WRITE_EXTERNAL_STORAGE" />
आयरनबेल्स

22
मैं भी sdcard पर भरोसा नहीं होता / sdcard स्थित जा रहा है, लेकिन Environment.getExternalStorageDirectory () के साथ पथ को पुनः प्राप्त
Axarydax

2
क्या मुझे उपयोग करना चाहिए: 16 * 1024 (16kb) मैं मेमोरी उपयोग और प्रदर्शन के बीच एक अच्छे संतुलन के रूप में 16K या 32K का विकल्प चुनता हूं।
नाम वउ

3
@rciovati को यह रनटाइम त्रुटि मिलीFailed to copy asset file: myfile.txt java.io.FileNotFoundException: myfile.txt at android.content.res.AssetManager.openAsset(Native Method)
likejudo

7
मेरे लिए यह कोड तभी काम करता है जब मैं इसे जोड़ता हूं: in = assetManager.open("images-wall/"+filename);जहां "छवियां-दीवार" संपत्ति के अंदर मेरा फ़ोल्डर है
अल्टिमो_म

62

आपके समाधान के आधार पर, मैंने सबफ़ोल्डर्स को अनुमति देने के लिए अपना स्वयं का कुछ किया। किसी को यह मददगार लग सकता है:

...

copyFileOrDir("myrootdir");

...

private void copyFileOrDir(String path) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path);
        } else {
            String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
            File dir = new File(fullPath);
            if (!dir.exists())
                dir.mkdir();
            for (int i = 0; i < assets.length; ++i) {
                copyFileOrDir(path + "/" + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}

private void copyFile(String filename) {
    AssetManager assetManager = this.getAssets();

    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open(filename);
        String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
        out = new FileOutputStream(newFileName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

}

1
assetManager.list(path)डिवाइस पर धीमा हो सकता है, संपत्ति पथ सूची बनाने के लिए पहले से ही इस स्निपेट का उपयोग assetsdir से किया जा सकता है :find . -name "*" -type f -exec ls -l {} \; | awk '{print substr($9,3)}' >> assets.list
alexkasko

3
अच्छा समाधान! केवल आवश्यक फ़िक्स को कॉपी करने के लिए अग्रणी विभाजकों को ट्रिम करना है CopyFileOrDir (): path = path.startsWith ("/")? path.substring (1): path;
Cross_

कुछ उपकरणों पर इस
स्टैक्वेरफ़्लो का

2
"/ data / data /" + this.getPackageName () को इस .getFilesDir () के साथ बदलें। getAbsolutePath ()
ibrahimyilmaz

1
... ( finallyब्लॉक में करीबी धाराएं ))
मिक्साज़

48

ऊपर दिए गए समाधान में कुछ त्रुटियों के कारण काम नहीं किया गया:

  • निर्देशिका निर्माण काम नहीं आया
  • Android द्वारा लौटाए गए संपत्तियों में तीन फ़ोल्डर भी होते हैं: चित्र, ध्वनि और वेबकिट
  • बड़ी फ़ाइलों से निपटने का तरीका जोड़ा गया: अपने प्रोजेक्ट में संपत्ति फ़ोल्डर में फ़ाइल में एक्सटेंशन .mp3 फ़ाइल जोड़ें और कॉपी के दौरान लक्ष्य फ़ाइल .mp3 एक्सटेंशन के बिना होगी।

यहाँ कोड है (मैंने लॉग स्टेटमेंट को छोड़ दिया है लेकिन आप उन्हें अभी छोड़ सकते हैं):

final static String TARGET_BASE_PATH = "/sdcard/appname/voices/";

private void copyFilesToSdCard() {
    copyFileOrDir(""); // copy all files in assets folder in my project
}

private void copyFileOrDir(String path) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
        Log.i("tag", "copyFileOrDir() "+path);
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path);
        } else {
            String fullPath =  TARGET_BASE_PATH + path;
            Log.i("tag", "path="+fullPath);
            File dir = new File(fullPath);
            if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                if (!dir.mkdirs())
                    Log.i("tag", "could not create dir "+fullPath);
            for (int i = 0; i < assets.length; ++i) {
                String p;
                if (path.equals(""))
                    p = "";
                else 
                    p = path + "/";

                if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                    copyFileOrDir( p + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}

private void copyFile(String filename) {
    AssetManager assetManager = this.getAssets();

    InputStream in = null;
    OutputStream out = null;
    String newFileName = null;
    try {
        Log.i("tag", "copyFile() "+filename);
        in = assetManager.open(filename);
        if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
            newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
        else
            newFileName = TARGET_BASE_PATH + filename;
        out = new FileOutputStream(newFileName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", "Exception in copyFile() of "+newFileName);
        Log.e("tag", "Exception in copyFile() "+e.toString());
    }

}

संपादित करें: एक गलत तरीके से ठीक किया गया ";" जो एक व्यवस्थित "फेंक रहा था" dir नहीं बना सका "त्रुटि।


4
यह समाधान बन जाना चाहिए!
मासिमो वेरोलो

1
नोट: Log.i ("टैग", "dir नहीं बना सका" + पूर्णपाठ); हमेशा जैसा होता है; अगर गलत है।
राउंडस्पारो हिल्टैक्स

awsome तरीका! बहुत बहुत धन्यवाद! लेकिन आप jpg फाइल क्यों चेक करते हैं?
फुओंग

32

मुझे पता है कि इसका उत्तर दिया जा चुका है लेकिन मेरे पास संपत्ति निर्देशिका से sdcard पर एक फ़ाइल में कॉपी करने का एक और अधिक सुंदर तरीका है। इसके लिए "लूप" की आवश्यकता नहीं है, बल्कि कार्य करने के लिए फ़ाइल स्ट्रीम और चैनल का उपयोग करता है।

(नोट) यदि किसी भी प्रकार की संपीड़ित फ़ाइल, एपीके, पीडीएफ, ... का उपयोग करके आप संपत्ति में डालने से पहले फ़ाइल एक्सटेंशन का नाम बदलना चाहते हैं और फिर एसडीकार्ड में कॉपी करते ही नाम बदल सकते हैं)

AssetManager am = context.getAssets();
AssetFileDescriptor afd = null;
try {
    afd = am.openFd( "MyFile.dat");

    // Create new file to copy into.
    File file = new File(Environment.getExternalStorageDirectory() + java.io.File.separator + "NewFile.dat");
    file.createNewFile();

    copyFdToFile(afd.getFileDescriptor(), file);

} catch (IOException e) {
    e.printStackTrace();
}

इसके माध्यम से लूप के बिना किसी फ़ाइल को कॉपी करने का तरीका।

public static void copyFdToFile(FileDescriptor src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

अन्य समाधानों पर यह पसंद आया, थोड़ा सा नट। खदान पर थोड़ा संशोधन जिसमें गुम फाइल बनाने वाले शामिल हैं। चियर्स!
क्रिस। जेनकिंस

3
यह मेरे लिए फ़ाइल डिस्क्रिप्टर के पिछले काम नहीं करेगा, This file can not be opened as a file descriptor; it is probably compressed- यह एक पीडीएफ फाइल है। जानिए कैसे तय करें?
Ga

1
यह मानता है कि inChannel.size () फ़ाइल के आकार का आकार लौटाता है। यह ऐसी कोई गारंटी नहीं देता है । मैं 2 फ़ाइलों के लिए 2.5 MiB प्राप्त कर रहा हूं जो कि 450 KiB हैं।
AI0867 12

1
मैंने अभी पाया है कि AssetFileDescriptor.getLength () सही फाइल को वापस कर देगा।
AI0867

1
उपरोक्त के अतिरिक्त, एसेट फ़ाइल डिस्क्रिप्टर में स्थान 0 पर शुरू नहीं हो सकता है। AssetFileDescriptor.getStartOffset () प्रारंभिक ऑफसेट लौटाएगा।
AI0867

5

इसे आज़माएं यह बहुत सरल है, इससे आपको मदद मिलेगी:

// Open your local db as the input stream
    InputStream myInput = _context.getAssets().open(YOUR FILE NAME);

    // Path to the just created empty db
    String outFileName =SDCARD PATH + YOUR FILE NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }
    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

5

यह कोटलिन में संक्षिप्त तरीका होगा।

    fun AssetManager.copyRecursively(assetPath: String, targetFile: File) {
        val list = list(assetPath)
        if (list.isEmpty()) { // assetPath is file
            open(assetPath).use { input ->
                FileOutputStream(targetFile.absolutePath).use { output ->
                    input.copyTo(output)
                    output.flush()
                }
            }

        } else { // assetPath is folder
            targetFile.delete()
            targetFile.mkdir()

            list.forEach {
                copyRecursively("$assetPath/$it", File(targetFile, it))
            }
        }
    }

सूची (एसेटपैथ)? चलो {...}, वास्तव में। यह अशक्त है।
गैबोर

4

यहां वर्तमान एंड्रॉइड डिवाइसों के लिए एक साफ किया गया संस्करण है, कार्यात्मक विधि डिजाइन ताकि आप इसे एक एसेट्सहेलर कैंप जैसे कॉपी कर सकें।)

/**
 * 
 * Info: prior to Android 2.3, any compressed asset file with an
 * uncompressed size of over 1 MB cannot be read from the APK. So this
 * should only be used if the device has android 2.3 or later running!
 * 
 * @param c
 * @param targetFolder
 *            e.g. {@link Environment#getExternalStorageDirectory()}
 * @throws Exception
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static boolean copyAssets(AssetManager assetManager,
        File targetFolder) throws Exception {
    Log.i(LOG_TAG, "Copying files from assets to folder " + targetFolder);
    return copyAssets(assetManager, "", targetFolder);
}

/**
 * The files will be copied at the location targetFolder+path so if you
 * enter path="abc" and targetfolder="sdcard" the files will be located in
 * "sdcard/abc"
 * 
 * @param assetManager
 * @param path
 * @param targetFolder
 * @return
 * @throws Exception
 */
public static boolean copyAssets(AssetManager assetManager, String path,
        File targetFolder) throws Exception {
    Log.i(LOG_TAG, "Copying " + path + " to " + targetFolder);
    String sources[] = assetManager.list(path);
    if (sources.length == 0) { // its not a folder, so its a file:
        copyAssetFileToFolder(assetManager, path, targetFolder);
    } else { // its a folder:
        if (path.startsWith("images") || path.startsWith("sounds")
                || path.startsWith("webkit")) {
            Log.i(LOG_TAG, "  > Skipping " + path);
            return false;
        }
        File targetDir = new File(targetFolder, path);
        targetDir.mkdirs();
        for (String source : sources) {
            String fullSourcePath = path.equals("") ? source : (path
                    + File.separator + source);
            copyAssets(assetManager, fullSourcePath, targetFolder);
        }
    }
    return true;
}

private static void copyAssetFileToFolder(AssetManager assetManager,
        String fullAssetPath, File targetBasePath) throws IOException {
    InputStream in = assetManager.open(fullAssetPath);
    OutputStream out = new FileOutputStream(new File(targetBasePath,
            fullAssetPath));
    byte[] buffer = new byte[16 * 1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
    in.close();
    out.flush();
    out.close();
}

4

इस SO उत्तर को @DannyA द्वारा संशोधित किया गया

private void copyAssets(String path, String outPath) {
    AssetManager assetManager = this.getAssets();
    String assets[];
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path, outPath);
        } else {
            String fullPath = outPath + "/" + path;
            File dir = new File(fullPath);
            if (!dir.exists())
                if (!dir.mkdir()) Log.e(TAG, "No create external directory: " + dir );
            for (String asset : assets) {
                copyAssets(path + "/" + asset, outPath);
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, "I/O Exception", ex);
    }
}

private void copyFile(String filename, String outPath) {
    AssetManager assetManager = this.getAssets();

    InputStream in;
    OutputStream out;
    try {
        in = assetManager.open(filename);
        String newFileName = outPath + "/" + filename;
        out = new FileOutputStream(newFileName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

}

तैयारी

src/main/assets नाम के साथ जोड़ें फ़ोल्डर मेंfold

प्रयोग

File outDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
copyAssets("fold",outDir.toString());

बाहरी निर्देशिका में उन सभी फ़ाइलों और निर्देशिकाओं का पता लगाएं जो तह संपत्ति के भीतर हैं


3

अपने फ़ोल्डर में संपत्ति से सभी फ़ाइलों और निर्देशिकाओं की प्रतिलिपि बनाएँ!

बेहतर उपयोग एपाचे कॉमन्स io की प्रतिलिपि बनाने के लिए

public void doCopyAssets() throws IOException {
    File externalFilesDir = context.getExternalFilesDir(null);

    doCopy("", externalFilesDir.getPath());

}

// यह मुख्य धातु है कॉपी के लिए

private void doCopy(String dirName, String outPath) throws IOException {

    String[] srcFiles = assets.list(dirName);//for directory
    for (String srcFileName : srcFiles) {
        String outFileName = outPath + File.separator + srcFileName;
        String inFileName = dirName + File.separator + srcFileName;
        if (dirName.equals("")) {// for first time
            inFileName = srcFileName;
        }
        try {
            InputStream inputStream = assets.open(inFileName);
            copyAndClose(inputStream, new FileOutputStream(outFileName));
        } catch (IOException e) {//if directory fails exception
            new File(outFileName).mkdir();
            doCopy(inFileName, outFileName);
        }

    }
}

public static void closeQuietly(AutoCloseable autoCloseable) {
    try {
        if(autoCloseable != null) {
            autoCloseable.close();
        }
    } catch(IOException ioe) {
        //skip
    }
}

public static void copyAndClose(InputStream input, OutputStream output) throws IOException {
    copy(input, output);
    closeQuietly(input);
    closeQuietly(output);
}

public static void copy(InputStream input, OutputStream output) throws IOException {
    byte[] buffer = new byte[1024];
    int n = 0;
    while(-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }
}

2

योरम कोहेन उत्तर के आधार पर, यहां एक संस्करण है जो गैर स्थैतिक लक्ष्य निर्देशिका का समर्थन करता है।

साथ Invoque copyFileOrDir(getDataDir(), "")लिखने के लिए आंतरिक एप्लिकेशन भंडारण फ़ोल्डर / डेटा / डाटा / pkg_name /

  • सबफ़ोल्डर्स का समर्थन करता है।
  • कस्टम और गैर-स्थिर लक्ष्य निर्देशिका का समर्थन करता है
  • "इमेजेज" आदि नकली एसेट फोल्डर को कॉपी करने से बचें

    private void copyFileOrDir(String TARGET_BASE_PATH, String path) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
        Log.i("tag", "copyFileOrDir() "+path);
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(TARGET_BASE_PATH, path);
        } else {
            String fullPath =  TARGET_BASE_PATH + "/" + path;
            Log.i("tag", "path="+fullPath);
            File dir = new File(fullPath);
            if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                if (!dir.mkdirs())
                    Log.i("tag", "could not create dir "+fullPath);
            for (int i = 0; i < assets.length; ++i) {
                String p;
                if (path.equals(""))
                    p = "";
                else 
                    p = path + "/";
    
                if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                    copyFileOrDir(TARGET_BASE_PATH, p + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
    }
    
    private void copyFile(String TARGET_BASE_PATH, String filename) {
    AssetManager assetManager = this.getAssets();
    
    InputStream in = null;
    OutputStream out = null;
    String newFileName = null;
    try {
        Log.i("tag", "copyFile() "+filename);
        in = assetManager.open(filename);
        if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
            newFileName = TARGET_BASE_PATH + "/" + filename.substring(0, filename.length()-4);
        else
            newFileName = TARGET_BASE_PATH + "/" + filename;
        out = new FileOutputStream(newFileName);
    
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", "Exception in copyFile() of "+newFileName);
        Log.e("tag", "Exception in copyFile() "+e.toString());
    }
    
    }

2

इस प्रश्न के उत्तर में कुछ अवधारणाओं का उपयोग करते हुए, मैंने एक कक्षा लिखी जिसे AssetCopierनकल को /assets/सरल बनाने के लिए कहा गया । यह पर उपलब्ध है GitHub और साथ पहुँचा जा सकता jitpack.io :

new AssetCopier(MainActivity.this)
        .withFileScanning()
        .copy("tocopy", destDir);

अधिक जानकारी के लिए https://github.com/flipagram/android-assetcopier देखें ।


2

ऐसा करने के लिए अनिवार्य रूप से दो तरीके हैं।

सबसे पहले, आप AssetManager.open का उपयोग कर सकते हैं , और जैसा कि रोहित नंदकुमार द्वारा वर्णित है और इनपुटस्ट्रीम पर पुनरावृति करता है।

दूसरे, आप उपयोग कर सकते हैं AssetManager.openFd , जिसे आप एक का उपयोग करने की अनुमति देता FileChannel (है जो [transferTo] ( https://developer.android.com/reference/java/nio/channels/FileChannel.html#transferTo(long , लंबा, java.nio.channels.WritableByteChannel)) और [transferFrom] ( https://developer.android.com/reference/java/nio/channels/FileChannel.html#titferFrom(java.nio.chanelines.ReadableByteChannel , लंबा लंबे)) तरीके), ताकि आपको इनपुट स्ट्रीम पर खुद को लूप न करना पड़े।

मैं यहाँ OpenFd विधि का वर्णन करूँगा।

दबाव

पहले आपको यह सुनिश्चित करने की आवश्यकता है कि फ़ाइल असंपीड़ित है। पैकेजिंग सिस्टम किसी भी फ़ाइल को एक्सटेंशन के साथ संपीड़ित करने के लिए चुन सकता है जो noCompress के रूप में चिह्नित नहीं है , और संपीड़ित फ़ाइलें मेमोरी मैप नहीं की जा सकती हैं, इसलिए आपको उस मामले में AssetManager.open पर भरोसा करना होगा ।

आप इसे संपीड़ित होने से रोकने के लिए अपनी फ़ाइल में '.mp3' एक्सटेंशन जोड़ सकते हैं, लेकिन उचित समाधान यह है कि आप अपने ऐप / बिल्ड.ग्रेड फ़ाइल को संशोधित करें और निम्न पंक्तियों को जोड़ें (पीडीएफ फाइलों के संपीड़न को अक्षम करने के लिए)

aaptOptions {
    noCompress 'pdf'
}

फ़ाइल पैकिंग

ध्यान दें कि पैकर अभी भी कई फाइलों को एक में पैक कर सकता है, इसलिए आप पूरी फाइल को नहीं पढ़ सकते हैं जो कि एसेटमैन आपको देता है। आपको AssetFileDescriptor से पूछना होगा कि आपको किन भागों की आवश्यकता है।

पैक्ड फ़ाइल का सही भाग ढूँढना

एक बार यह सुनिश्चित किया है कि आपकी फ़ाइल असम्पीडित संग्रहीत किया जाता है, तो आप उपयोग कर सकते हैं AssetManager.openFd एक प्राप्त करने के लिए विधि AssetFileDescriptor है, जो एक प्राप्त करने के लिए इस्तेमाल किया जा सकता FileInputStream (विपरीत AssetManager.open है, जो एक रिटर्न InputStream ) है कि एक शामिल FileChannel । इसमें शुरुआती ऑफसेट (getStartOffset) और आकार (getLength) भी शामिल है , जिसे आपको फ़ाइल के सही भाग को प्राप्त करने की आवश्यकता है।

कार्यान्वयन

एक उदाहरण कार्यान्वयन नीचे दिया गया है:

private void copyFileFromAssets(String in_filename, File out_file){
    Log.d("copyFileFromAssets", "Copying file '"+in_filename+"' to '"+out_file.toString()+"'");
    AssetManager assetManager = getApplicationContext().getAssets();
    FileChannel in_chan = null, out_chan = null;
    try {
        AssetFileDescriptor in_afd = assetManager.openFd(in_filename);
        FileInputStream in_stream = in_afd.createInputStream();
        in_chan = in_stream.getChannel();
        Log.d("copyFileFromAssets", "Asset space in file: start = "+in_afd.getStartOffset()+", length = "+in_afd.getLength());
        FileOutputStream out_stream = new FileOutputStream(out_file);
        out_chan = out_stream.getChannel();
        in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan);
    } catch (IOException ioe){
        Log.w("copyFileFromAssets", "Failed to copy file '"+in_filename+"' to external storage:"+ioe.toString());
    } finally {
        try {
            if (in_chan != null) {
                in_chan.close();
            }
            if (out_chan != null) {
                out_chan.close();
            }
        } catch (IOException ioe){}
    }
}

यह उत्तर JPM के उत्तर पर आधारित है ।


1
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        copyReadAssets();
    }


    private void copyReadAssets()
    {
        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;

        String strDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ File.separator + "Pdfs";
        File fileDir = new File(strDir);
        fileDir.mkdirs();   // crear la ruta si no existe
        File file = new File(fileDir, "example2.pdf");



        try
        {

            in = assetManager.open("example.pdf");  //leer el archivo de assets
            out = new BufferedOutputStream(new FileOutputStream(file)); //crear el archivo


            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            Log.e("tag", e.getMessage());
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Pdfs" + "/example2.pdf"), "application/pdf");
        startActivity(intent);
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }
}

कोड के कुछ हिस्सों को इस तरह बदलें:

out = new BufferedOutputStream(new FileOutputStream(file));

उदाहरण के लिए .txt के पहले उदाहरण Pdfs के लिए है

FileOutputStream fos = new FileOutputStream(file);

1

AssetManager का उपयोग करें , यह परिसंपत्तियों में फ़ाइलों को पढ़ने की अनुमति देता है। फिर sdcard के लिए फ़ाइलों को लिखने के लिए नियमित जावा IO का उपयोग करें।

Google आपका मित्र है, उदाहरण के लिए खोजें।


1

हाय दोस्तों मैंने कुछ इस तरह किया। एन-वें गहराई से कॉपी करने के लिए फ़ोल्डर और फ़ाइलों की प्रतिलिपि बनाएँ। जो आपको Android AssetManager से कॉपी करने के लिए सभी निर्देशिका संरचना को कॉपी करने की अनुमति देता है :)

    private void manageAssetFolderToSDcard()
    {

        try
        {
            String arg_assetDir = getApplicationContext().getPackageName();
            String arg_destinationDir = FRConstants.ANDROID_DATA + arg_assetDir;
            File FolderInCache = new File(arg_destinationDir);
            if (!FolderInCache.exists())
            {
                copyDirorfileFromAssetManager(arg_assetDir, arg_destinationDir);
            }
        } catch (IOException e1)
        {

            e1.printStackTrace();
        }

    }


    public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException
    {
        File sd_path = Environment.getExternalStorageDirectory(); 
        String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir);
        File dest_dir = new File(dest_dir_path);

        createDir(dest_dir);

        AssetManager asset_manager = getApplicationContext().getAssets();
        String[] files = asset_manager.list(arg_assetDir);

        for (int i = 0; i < files.length; i++)
        {

            String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];
            String sub_files[] = asset_manager.list(abs_asset_file_path);

            if (sub_files.length == 0)
            {
                // It is a file
                String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];
                copyAssetFile(abs_asset_file_path, dest_file_path);
            } else
            {
                // It is a sub directory
                copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);
            }
        }

        return dest_dir_path;
    }


    public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException
    {
        InputStream in = getApplicationContext().getAssets().open(assetFilePath);
        OutputStream out = new FileOutputStream(destinationFilePath);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
        in.close();
        out.close();
    }

    public String addTrailingSlash(String path)
    {
        if (path.charAt(path.length() - 1) != '/')
        {
            path += "/";
        }
        return path;
    }

    public String addLeadingSlash(String path)
    {
        if (path.charAt(0) != '/')
        {
            path = "/" + path;
        }
        return path;
    }

    public void createDir(File dir) throws IOException
    {
        if (dir.exists())
        {
            if (!dir.isDirectory())
            {
                throw new IOException("Can't create directory, a file is in the way");
            }
        } else
        {
            dir.mkdirs();
            if (!dir.isDirectory())
            {
                throw new IOException("Unable to create directory");
            }
        }
    }

अंत में एक Asynctask बनाएँ:

    private class ManageAssetFolders extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... arg0)
        {
            manageAssetFolderToSDcard();
            return null;
        }

    }

इसे अपनी गतिविधि से कॉल करें:

    new ManageAssetFolders().execute();

1

एक फ़ोल्डर को कॉपी करने और कस्टम गंतव्य को समायोजित करने के लिए उपरोक्त उत्तर का थोड़ा संशोधन।

public void copyFileOrDir(String path, String destinationDir) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path,destinationDir);
        } else {
            String fullPath = destinationDir + "/" + path;
            File dir = new File(fullPath);
            if (!dir.exists())
                dir.mkdir();
            for (int i = 0; i < assets.length; ++i) {
                copyFileOrDir(path + "/" + assets[i], destinationDir + path + "/" + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}

private void copyFile(String filename, String destinationDir) {
    AssetManager assetManager = this.getAssets();
    String newFileName = destinationDir + "/" + filename;

    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open(filename);
        out = new FileOutputStream(newFileName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
    new File(newFileName).setExecutable(true, false);
}

1

रोहित नंदकुमार के समाधान के आधार पर, मैंने संपत्ति के एक सबफ़ोल्डर (यानी "संपत्ति / MyFolder ") से फ़ाइलों की प्रतिलिपि बनाने के लिए खुद से कुछ किया । इसके अलावा, मैं जाँच कर रहा हूँ कि क्या फाइल फिर से कॉपी करने की कोशिश करने से पहले ही sdcard में मौजूद है।

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("MyFolder");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open("MyFolder/"+filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          if (!(outFile.exists())) {// File does not exist...
                out = new FileOutputStream(outFile);
                copyFile(in, out);
          }
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }     
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
        }  
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

0

यह अब तक का सबसे अच्छा समाधान है जो मैं इंटरनेट पर पा सकता हूं। मैंने निम्नलिखित लिंक https://gist.github.com/mhasby/026f02b33fcc4207b302a60645f6e217 का उपयोग किया है ,
लेकिन इसमें एक ही त्रुटि थी जिसे मैंने ठीक किया और फिर यह एक आकर्षण की तरह काम करता है। यहाँ मेरा कोड है। आप इसे आसानी से उपयोग कर सकते हैं क्योंकि यह एक स्वतंत्र जावा वर्ग है।

public class CopyAssets {
public static void copyAssets(Context context) {
    AssetManager assetManager = context.getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(filename);

            out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/www/resources/" + filename);
            copyFile(in, out);
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {

                }
            }
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                    out = null;
                } catch (IOException e) {

                }
            }
        }
    }
}

public static void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}}

जैसा कि आप देख सकते हैं, बस CopyAssetsअपने जावा वर्ग का एक उदाहरण बनाएं जिसमें एक गतिविधि हो। अब इस हिस्से, जहाँ तक मेरी परीक्षण के रूप में और इंटरनेट पर शोध महत्वपूर्ण है, You cannot use AssetManager if the class has no activity। इसका जावा वर्ग के संदर्भ से कुछ लेना-देना है।
अब, c.copyAssets(getApplicationContext())विधि का उपयोग करने का एक आसान तरीका है, जहां कक्षा का cउदाहरण और उदाहरण है CopyAssets। अपनी आवश्यकता के अनुसार, मैंने प्रोग्राम को assetफ़ोल्डर के अंदर अपने सभी संसाधन फ़ाइलों /www/resources/को मेरी आंतरिक निर्देशिका के फ़ोल्डर में कॉपी करने की अनुमति दी ।
आप आसानी से उस भाग का पता लगा सकते हैं जहाँ आपको अपने उपयोग के अनुसार निर्देशिका में परिवर्तन करने की आवश्यकता है। अगर आपको किसी मदद की ज़रूरत हो तो मुझे बेझिझक पिंग करें।


0

जो लोग कोटलिन के लिए अद्यतन कर रहे हैं:

बचने के इस कदम के बाद FileUriExposedExceptions, उपयोगकर्ता को WRITE_EXTERNAL_STORAGEअनुमति देने की अनुमति दी गई है और आपकी फ़ाइल अंदर है assets/pdfs/mypdf.pdf

private fun openFile() {
    var inputStream: InputStream? = null
    var outputStream: OutputStream? = null
    try {
        val file = File("${activity.getExternalFilesDir(null)}/$PDF_FILE_NAME")
        if (!file.exists()) {
            inputStream = activity.assets.open("$PDF_ASSETS_PATH/$PDF_FILE_NAME")
            outputStream = FileOutputStream(file)
            copyFile(inputStream, outputStream)
        }

        val uri = FileProvider.getUriForFile(
            activity,
            "${BuildConfig.APPLICATION_ID}.provider.GenericFileProvider",
            file
        )
        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(uri, "application/pdf")
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
        }
        activity.startActivity(intent)
    } catch (ex: IOException) {
        ex.printStackTrace()
    } catch (ex: ActivityNotFoundException) {
        ex.printStackTrace()
    } finally {
        inputStream?.close()
        outputStream?.flush()
        outputStream?.close()
    }
}

@Throws(IOException::class)
private fun copyFile(input: InputStream, output: OutputStream) {
    val buffer = ByteArray(1024)
    var read: Int = input.read(buffer)
    while (read != -1) {
        output.write(buffer, 0, read)
        read = input.read(buffer)
    }
}

companion object {
    private const val PDF_ASSETS_PATH = "pdfs"
    private const val PDF_FILE_NAME = "mypdf.pdf"
}
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.