伙计们,我的网址中有一个文本文件。点击一个按钮,我可以将其下载到SD卡。
但是我需要用raw文件夹中的文件替换下载的文件。两者都是不同的文件。
这是我从网址下载的方式
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/varun");
dir.mkdirs();
try {
u = new URL("http://hihowru.com/123.xml");
file = new File(dir,"123.xml");
startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + "a.mp3");
URLConnection uconnection = u.openConnection();
InputStream is = uconnection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos;
fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Toast toast = Toast.makeText(getApplicationContext(), "Downloaded to Sdcard/varun"+audioxml, 0);
toast.show();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
Intent ii = new Intent(DownloadFiles.this,Relaxation.class);
startActivity(ii);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但我需要将此文件(下载的文件)替换为原始文件夹中的文件
下载文件名:hi.txt 原始文件夹名称:hw.txt
如何实现这一点请帮助
答案 0 :(得分:0)
您无法修改或编写android resources
或asset
目录中的文件。因为android apk文件是read only
。所以你只能阅读它。最好的方法是复制internal storage
中的文件然后从该路径使用,也可以在url下载文件后更新内部存储路径。
更新:
从/ asset到应用程序内部存储的复制文件的代码。
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}