Android 从internet下载.txt文件
可能重复:Android 从internet下载.txt文件,android,url,text,storage,Android,Url,Text,Storage,可能重复: 我如何从互联网上以给定的URL下载一个.txt文件并将其保存到Android手机上?它可以保存到内部存储器、SD存储器或任何可供应用程序使用的真正可访问的位置 我用来测试加载URL Web视图的URL是,这应该可以做到。它将文件下载到sdcard/Download/products.txt。你可以在下面更改它 try { URL url = new URL("http://base.google.com/base/products.txt"); URLConnect
我如何从互联网上以给定的URL下载一个.txt文件并将其保存到Android手机上?它可以保存到内部存储器、SD存储器或任何可供应用程序使用的真正可访问的位置
我用来测试加载URL Web视图的URL是,这应该可以做到。它将文件下载到
sdcard/Download/products.txt
。你可以在下面更改它
try {
URL url = new URL("http://base.google.com/base/products.txt");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/products.txt");
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
/*publishProgress("" + progress_temp); //only for asynctask
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}*/
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
}
这应该能奏效。它将文件下载到
sdcard/Download/products.txt
。你可以在下面更改它
try {
URL url = new URL("http://base.google.com/base/products.txt");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/products.txt");
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
/*publishProgress("" + progress_temp); //only for asynctask
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}*/
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
}
初始化变量
progress
后,引用了未知变量count
。我可以假定count
应该是progress
?对不起!添加int计数代码>可访问的位置。编辑我的答案!初始化变量progress
后,引用了未知变量count
。我可以假定count
应该是progress
?对不起!添加int计数代码>可访问的位置。编辑我的答案!