我将从浏览器下载文件并存储在设备的内部存储中,路径显示为 /data/data/com.example/files/downloads/sample.pdf 但是第二天我将文件路径视为空“”
使用以下代码从浏览器保存文件:
private String downloadfile(Uri uri) {
int count;
String fileName = "";
try {
// Output stream to write file
String root = null;
// if (Environment.isExternalStorageRemovable())
// else
root = getFilesDir().toString()+ "/download/";
File file = new File(root);
if (!file.exists())
file.mkdirs();
fileName = file.getAbsolutePath();
file = new File("" + uri);
fileName = fileName + "/" + file.getName();
URL url = new URL(uri.toString());
URLConnection conection = url.openConnection();
conection.setRequestProperty("Content-Type",
"application/octet-stream");
conection.setRequestProperty("Expect", "100-continue");
conection.setRequestProperty("Content-Disposition", "attachment");
conection.setRequestProperty("filename", file.getName());
conection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(fileName);
file = new File(fileName);
file.createNewFile();
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
String inputs = "EX";
Parameter.trackApplication(inputs, e.getMessage());
e.printStackTrace();
}
return fileName;
}
我如何解决这个问题,请在我出错的地方纠正我并帮助我解决这个问题。