Calling a file path from the android workspace folder

前端 未结 3 993
说谎
说谎 2021-01-23 14:16

Basically I have right clicked on my project name and successfully created a new folder called pdfs. I want to pre load some pdf files in here so how would I call this path/some

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 15:01

    Your new folder will be completely ignored by the builders. It will not be packaged with your app and copied onto any emulator or device. If you want to package data with your app, you need to use the raw or assets folders. The latter allows subfolders, so you could move your pdfs folder there.

    Here's some code that will move files from assets/pdfs to files/pdfs under your app's designated external directory.

    final static String TAG = "MainActivity";
    final static int BUFF_SIZE = 2048;
    
    private void copyPdfs() {
        AssetManager assetManager = getAssets();
        String[] pdfs = null;
        try {
            pdfs = assetManager.list("pdfs");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "Unable to get list of PDFs!");
        }
    
        File pdfDir = new File(getExternalFilesDir(null), "pdfs");
        if (!pdfDir.exists()) {
            Log.d(TAG, "Creating directory " + pdfDir.getAbsolutePath());
            pdfDir.mkdirs();
        }
    
        for (String pdf : pdfs) {
            Log.d(TAG, "Copying " + pdf);
            InputStream in = null;
            OutputStream out = null;
    
            try {
                in = assetManager.open("pdfs" + File.separator +  pdf);
                out = new FileOutputStream(new File(pdfDir, pdf));
    
                copyPdf(in, out);
    
                out.close();
                in.close();
    
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "Unable to copy PDF!");
            }
        }
    }
    
    private void copyPdf(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[BUFF_SIZE];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1)
            out.write(buffer, 0, bytesRead);
    
        out.flush();        
    }
    

提交回复
热议问题