我正在尝试从我的Android项目中的URL保存pdf文件,但是当它保存.pdf文件时,它的维度为0KB。代码创建目录和PDF文件(Ciao.pdf),我的AndroidManifest.xml中也有INTERNET和WRITE_EXTERNAL_STORAGE权限。 这是代码:
LinkTo = "http://www.ancestralauthor.com/download/sample.pdf";
Toast.makeText(getApplicationContext(),LinkTo, Toast.LENGTH_LONG).show();
String storage = Environment.getExternalStorageState();
Log.i("System out", "" + storage);
File rootsd = Environment.getExternalStorageDirectory();
Log.d("ROOT PATH", "" + rootsd.getAbsolutePath());
File mydir = new File(rootsd.toString() + "/unplugger");
Log.i("DIR PATH", "" + mydir.getAbsolutePath());
mydir.mkdir();
URL u;
try {
u = new URL(LinkTo);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(mydir + "/"
+ "Ciao.pdf"));
InputStream input = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = input.read(buffer)) > 0) {
f.write(buffer, 0, len1);
f.flush();
}
f.close();
c.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("System out","malformed :"+e.getMessage());
Log.i("System out","malformed :"+e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("System out","io: "+e.getMessage());
Log.i("System out","io: "+e.toString());
}