gpt4 book ai didi

android - 如何从服务器下载XML文件并保存到SD卡?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:52:51 24 4
gpt4 key购买 nike

在我的应用程序中,我尝试从服务器下载 XML 文件并将其存储在 SD 卡中。为此,我使用以下代码......

        try {
File root = android.os.Environment.getExternalStorageDirectory();

File dir = new File (root.getAbsolutePath() + "/project");
if(dir.exists()==false) {
dir.mkdirs();
}

URL url = new URL("url"); //you can write here any link
File file = new File(dir, name);

long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + name);

/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();

/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);

/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}



/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

} catch (IOException e) {
e.printStackTrace();
}

这给我 java.net.SocketException: The operation timed out 异常...请帮助我..我是 android 开发的新手

最佳答案

public void DownloadFiles(){

try {
URL url = new URL("http://nodeload.github.com/nexes/Android-File-Manager/zipball/master");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Folder");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/zip.zip");
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

关于android - 如何从服务器下载XML文件并保存到SD卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com