我在Android应用程序中工作,我想将我的PDF保存在临时文件夹中,然后我成功保存了它。但是我无法检索PDF并在adobe reader中查看它。它说“文件或文件夹未找到”。
请查看我的代码。
private final String TEMP_FILE_NAME = "wpta_temp_file1.pdf";
private File tempFile=null;
//Method to download the pdf and save to temp folder
public void downloadHTTP(String imageURL) {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
long startTime = System.currentTimeMillis();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new UsernamePasswordCredentials("username",
"password"));
HttpGet httpget = new HttpGet(imageURL);
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/** Getting Cache Directory */
//File cDir = getBaseContext().getCacheDir();
File cDir= getExternalFilesDir(null);
/** Getting a reference to temporary file, if created earlier */
tempFile = new File(cDir.getPath() + "/" + TEMP_FILE_NAME);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
}
// EntityUtils.consume(entity);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
//Open the pdf saved in the temp folder
public void showPdf() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(tempFile), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
} catch (Exception e) {
// No application to view, ask to download one
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("No Application Found");
builder.setMessage("Download one from Android Market?");
builder.setPositiveButton("Yes, Please",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri
.parse("market://details?id=com.adobe.reader"));
startActivity(marketIntent);
}
});
builder.setNegativeButton("No, Thanks", null);
builder.create().show();
}
}
答案 0 :(得分:2)
getCachedir()
提供了一个专用于您应用的目录。其他应用无法访问。更好地使用getExternalFilesDir()
。