您在哪个路径存储 pdf 文件?
请参阅下面的一个从 android Assets 获取文件并将其复制到特定的 sdcard 位置。
我将首先检查 pdf 文件是否已在期望路径中可用。
File file1 = new File("/sdcard/SampleProjectApp/WindsorONE_Mobile_Molding.pdf");
File file2 = new File("/sdcard/SampleProjectApp/WindsorONE_Mobile_PK.pdf");
File file3 = new File("/sdcard/SampleProjectApp/Alone.mp4");
if(!((file1.exists())) || !((file2.exists())) || !((file3.exists()))) {
ArrayList<String> files = new ArrayList<String>();
files.add("WindsorONE_Mobile_Molding.pdf");
files.add("WindsorONE_Mobile_PK.pdf");
files.add("Alone.mp4");
new myAsyncTask().execute(files);
}
现在,如果该位置不存在该文件,那么它将执行 myAsyncTask 以将文件从资产复制到 SdCard。
// AsyncTass for the Progress Dialog and to do Background Process
private class myAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ListSample.this, "W1 SALES (beta)", "Loading...");
}
@Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileFromAssetsToSDCard(files.get(i));
} return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file from Assets to the SDCard
public void copyFileFromAssetsToSDCard(String fileFromAssets){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFromAssets);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/SampleProjectApp", fileFromAssets));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
更新
就你而言:
替换
SampleProjectApp/WindsorONE_Mobile_Molding.pdf
和
Android/data/com.project.projectname/cache/YOUR_PDF_FILE.pdf
希望它有意义。
更新 2
下面的代码是将文件从一个路径复制到另一个路径。您只需传递文件所在的路径和必须复制的路径。
代码:
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}