27
public void DOCS(View btnDocs)
{   
    File fileBrochure = new File("android.resource://com.project.datastructure/assets/abc.pdf");
    if (!fileBrochure.exists())
    {
         CopyAssetsbrochure();
    } 

    /** PDF reader code */
    File file = new File("android.resource://com.project.datastructure/assets/abc.pdf");        

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file),"application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try 
    {
        getApplicationContext().startActivity(intent);
    } 
    catch (ActivityNotFoundException e) 
    {
         Toast.makeText(Stack_dr.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }
}
private void CopyAssetsbrochure() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try 
    {
        files = assetManager.list("");
    } 
    catch (IOException e){}
    for(int i=0; i<files.length; i++)
    {
        String fStr = files[i];
        if(fStr.equalsIgnoreCase("abc.pdf"))
        {
            InputStream in = null;
            OutputStream out = null;
            try 
            {
              in = assetManager.open(files[i]);
              out = new FileOutputStream("/sdcard/" + files[i]);
              copyFile(in, out);
              in.close();
              in = null;
              out.flush();
              out.close();
              out = null;
              break;
            } 
            catch(Exception e){}
        }
    }
}

 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);
    }
}

アプリケーションフォルダーにあるアセットフォルダーから pdf ファイルを読み込もうとしています。DOCSボタンをクリックすると、ポップアップが表示され、PDFを開くためのアプリケーション、つまり「abc.pdf」を選択できますが、オプションを選択すると、「ファイルパスが無効です」というエラーメッセージが表示されます。コードで指定したパスに問題があると思います。助けてください

4

11 に答える 11

6

これには回答がありましたが、含めるのが少し簡単だと思うので、私の解決策を共有したいと思いました。

使用法:

new OpenLocalPDF(context, 'nameOfPDFStoredInAssets').execute()

そして、ここにOpenLocalPDFクラスがあります:

public class OpenLocalPDF {

    private static String TAG = OpenLocalPDF.class.getSimpleName();

    private WeakReference<Context> contextWeakReference;
    private String fileName;

    public OpenLocalPDF(Context context, String fileName) {
        this.contextWeakReference = new WeakReference<>(context);
        this.fileName = fileName.endsWith("pdf") ? fileName : fileName + ".pdf";
    }

    public void execute() {

        Context context = contextWeakReference.get();
        if (context != null) {
            new CopyFileAsyncTask().execute();
        }

    }


    private class CopyFileAsyncTask extends AsyncTask<Void, Void, File> {


        final String appDirectoryName = BuildConfig.APPLICATION_ID;
        final File fileRoot = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), appDirectoryName);

        @Override
        protected File doInBackground(Void... params) {

            Context context = contextWeakReference.get();

            AssetManager assetManager = context.getAssets();

            File file = new File(fileRoot, fileName);

            InputStream in = null;
            OutputStream out = null;
            try {

                file.mkdirs();

                if (file.exists()) {
                    file.delete();
                }

                file.createNewFile();


                in = assetManager.open(fileName);
                Log.d(TAG, "In");

                out = new FileOutputStream(file);
                Log.d(TAG, "Out");

                Log.d(TAG, "Copy file");
                copyFile(in, out);

                Log.d(TAG, "Close");
                in.close();

                out.flush();
                out.close();

                return file;
            } catch (Exception e)
            {
                Log.e(TAG, e.getMessage());
            }

            return null;
        }

        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);
            }
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);

            Context context = contextWeakReference.get();


            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(
                    Uri.fromFile(file),
                    "application/pdf");

            context.startActivity(intent);

        }
    }
}

この許可を追加しますManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2016-12-18T20:47:01.120 に答える
3

sunsilのように、外部ディレクトリの場合です。

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));

前の例は Pdfs 用で、例の .txt の場合

FileOutputStream fos = new FileOutputStream(file);
于 2015-05-28T21:43:56.093 に答える
1

これは私にとってはうまくいきます。

ステップ 1: MainActivity.java 内

public class SampleActivity extends Activity  {

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

    //call this method by passing file name in params.
    readFromAssets("User guide.pdf");
 }

public static void readFromAssets(String fileName) {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(mContext.getFilesDir(), fileName);
    try {
        in = assetManager.open(fileName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            out = mContext.openFileOutput(file.getName(), Context.MODE_PRIVATE);
        } else {
            out = mContext.openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
        }
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
    Uri pdfFileURI;
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        pdfFileURI = FileProvider.getUriForFile(mContext,
                BuildConfig.APPLICATION_ID + ".provider", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        pdfFileURI = Uri.parse("file://" + mContext.getFilesDir() + "/" + fileName);
    }
    intent.setDataAndType(pdfFileURI, "application/pdf");
    mContext.startActivity(intent);
 }

   private 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);
     }
   }
}

ステップ 2:provider_paths.xml内に作成しますres->xml->provider_paths.xml。こちらをご覧ください

<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-path
    name="external"
    path="." />
  <root-path
    name="root"
    path="." />
</paths>

ステップ 3: AndroidManifest.xml で

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppThemeMaterial">

  <!-- INSIDE APPLICATION TAG -->

  <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
  </provider>
</application>     
于 2020-04-21T08:00:06.740 に答える