gpt4 book ai didi

java - 从 assets 文件夹中读取 pdf 文件

转载 作者:IT老高 更新时间:2023-10-28 20:50:05 24 4
gpt4 key购买 nike

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

我正在尝试从我的应用程序文件夹中的 assets 文件夹中读取一个 pdf 文件。当我点击我的 DOCS 按钮时,一切正常,弹出一个让我选择打开 pdf 的应用程序,即“abc.pdf”,但在选择一个选项后,我收到一条错误消息“文件路径无效”。我认为它们与我在代码中指定的路径存在一些问题。请帮忙

最佳答案

试试这个

public class SampleActivity extends Activity
{

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

}

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

InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "abc.pdf");
try
{
in = assetManager.open("abc.pdf");
out = 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());
}

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/abc.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);
}
}

}

确保包含

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

在 list 中

关于java - 从 assets 文件夹中读取 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17085574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com