我的文件res/raw
夹中有一些音频文件。由于某些原因,我想将此文件复制到我的 SDCard 时,我的应用程序启动。
我该怎么做?有人指导我吗?
我的文件res/raw
夹中有一些音频文件。由于某些原因,我想将此文件复制到我的 SDCard 时,我的应用程序启动。
我该怎么做?有人指导我吗?
从资源中读取,写入 SD 卡上的文件:
InputStream in = getResources().openRawResource(R.raw.myresource);
FileOutputStream out = new FileOutputStream(somePathOnSdCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
这是我用来完成这项工作的一种方法,该方法接收资源 id 和存储所需的名称,例如:
copyFiletoExternalStorage(R.raw.mysound, "jorgesys_sound.mp3");
方法:
private void copyFiletoExternalStorage(int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
环境。getExternalStorageDirectory()此方法在 API 级别 29 中已弃用,并且不允许在给定路径上创建目录/文件。
下面的代码用于创建目录并从 /res/raw 目录下载文件。
如果您的设备具有Android 10(API 级别 29)或更高版本,它将在以下位置下载您的文件
文件管理器 --> 存储 --> Android --> 数据 --> com.yourapp.packagename --> 文件 --> FOLDER_NAME --> file_name.png
private void downloadFileFromRawFolder(){
try {
InputStream in = getResources().openRawResource(
getResources().getIdentifier("file_name",
"raw", getPackageName())); // use only file name here, don't use extension
File fileWithinMyDir = new File(checkFolder(), "file_name.png"); //Getting a file within the dir.
Log.e("FILEPATH ", "fileWithinMyDir " + fileWithinMyDir);
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
byte[] buff = new byte[1024 * 1024 * 2]; //2MB file
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
Log.d(TAG, "Download Done ");
} catch (IOException e) {
Log.e(TAG, "Download Failed " + e.getMessage());
e.printStackTrace();
}
}
/* 创建目录 */
private File checkFolder() {
String path;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
path = getExternalFilesDir(null).getAbsolutePath() + "FOLDER_NAME";
} else {
path = Environment.getExternalStorageDirectory() + "FOLDER_NAME";
}
File dir = new File(path);
boolean isDirectoryCreated = dir.exists();
if (!isDirectoryCreated) {
isDirectoryCreated = dir.mkdir();
Log.d("Folder", "Created = " + isDirectoryCreated);
}
Log.d("Folder", "Created ? " + isDirectoryCreated);
return dir;
}
}