[英]Copying directories and files from res/raw folder to sd card - android
我有一個文件夾,其中包含幾個文件和一些目錄,我需要在我第一次啟動應用程序時復制到我的SD卡的/ mnt / sdcard / Android / data / path,當然,如果還沒有所需的文件夾在那條路上不存在。
我將把這個文件夾放在我的應用程序的res / raw文件夾中。
我需要做的一步一步的程序是什么,我可以將文件夾及其所有內容從res / raw復制到SD卡中的指定路徑。
任何幫助深表感謝。
編輯
以下是幫助其他人的解決方案:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
copyFileOrDir("edu1");//directory name in assets
}
File sdCard = Environment.getExternalStorageDirectory();
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
File dir = new File (sdCard.getAbsolutePath() + "/" + "Android/data");
//String fullPath = "/data/data/" + this.getPackageName() + "/" + path;//path for storing internally to data/data
//File dir = new File(fullPath);
if (!dir.exists()){
System.out.println("Created directory"+sdCard.getAbsolutePath() + "/Android/data");
boolean result = dir.mkdir();
System.out.println("Result of directory creation"+result);
}
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
System.out.println("Exception in copyFileOrDir"+ex);
}
}
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;//path for storing internally to data/data
String newFileName = sdCard.getAbsolutePath() + "/Android/data/" + 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) {
System.out.println("Exception in copyFile"+e);
}
}
}
我建議你將文件保存在資產中。 以下代碼可以幫助您將資產目錄中的內容復制到SD卡。
public static void copyFile(Activity c, String filename)
{
AssetManager assetManager = c.getAssets();
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(filename);
String newFileName = sdcardpath/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) {
Utility.printLog("tag", e.getMessage());
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
printLog(TAG, "Exception while closing input stream",e);
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
printLog(TAG, "Exception while closing output stream",e);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.