在我的资产文件夹中,我有一个名为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);
}
}
@覆盖 protected Void doInBackground(Void ... params){ // TODO自动生成的方法存根 CopyAssets(); return null; }
}
}
答案 0 :(得分:3)
试试这段代码
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;
}
答案 1 :(得分:0)
要在外部存储中写入数据,我们必须在AndroidManifest.xml中授予权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
现在你更新了logcat你可以使用AsyncTask或Handler来解决这个错误。