[英]Copy pdf file from asset to sd card
在我的資產文件夾中,我有一個名為lecture.pdf的pdf文件。 我試圖將此文件從資產復制到SD卡,以便從我的應用程序中讀取pdf,但該文件無法在SD卡上寫入。 誰能告訴我我做錯了什么。 這是寫入sd卡目錄的代碼
公共類XAclass擴展Activity {
WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.large);
new Asyntasking();
Intent intent = new Intent(getParent(), MyPdfViewerActivity.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME,
"mnt/sdcard/mylecture/lecture.pdf");
startActivity(intent);
}
private class Asyntasking extends AsyncTask<Void,Void,Void>
{
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = {};
try {
files = assetManager.list("lecture.pdf");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in= null;
OutputStream out = null;
try {
in = assetManager.open("/mnt/sdcard/mylecture/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream("/mnt/sdcard/mylecture/"+filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
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 doInBackground(Void ... params){// TODO自動生成的方法stub CopyAssets(); return null; }
}
}
試試這段代碼
private class Asyntasking extends AsyncTask<Void,Void,Void>
{
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = {};
try {
files = assetManager.list("Files");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in= null;
OutputStream out = null;
try {
in = assetManager.open("Files/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(exportDirectory+filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
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 doInBackground(Void... params) {
// TODO Auto-generated method stub
CopyAssets();
return null;
}
要在外部存儲中寫入數據,我們必須在AndroidManifest.xml中授予權限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
現在你更新了logcat你可以使用AsyncTask或Handler解決這個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.