(新手笔记,参考谨慎)
关于sd卡的存读删,网上有很多例子。但是一般都是以存储.txt文件为例,当要将音乐文件存入sd卡该如何呢?
public class SDcardData {
public static final String STORE_PATH = Environment.getExternalStorageDirectory() + "/ting/";
/**
*
* @param filename
* @return /sdcard/ting/filename
*/
public static File createFile(String filename) {
return createFile(STORE_PATH, filename);
}
public static File createFile(String path, String filename) {
File file = createDir(path);
File dir = new File(file, filename);
if (!dir.exists()) {
try {
//在指定的文件夹中创建文件
dir.createNewFile();
} catch (Exception e) {
}
}
return dir;
}
public static File createDir(String path){
File file = new File(path);
if (!file.exists()) {
try {
file.mkdirs();
} catch (Exception e) {
}
}
return file;
}
/**
* 将一个InputStream里面的数据写入到SD卡中
*
* @param path
* @param fileName
* @param input
* @return
*/
public File writeToSDFromInput(String fileName, InputStream input){
File file = null;
OutputStream output = null;
try {
file = createFile(fileName);
output = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
while((input.read(buffer)) != -1){
output.write(buffer);
}
//清缓存,将流中的数据保存到文件中
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
/**
*
* @param filename
* @return
*/
public static File getFile(String filename){
return getFile(STORE_PATH, filename);
}
public static File getFile(String path, String filename){
if(UtilsString.isEmpty(filename)) return null;
File dir = createDir(path);
return new File(dir, filename);
}
/**
*
* @param filename
*/
public static void deleteFiles(String filename){
File f = getFile(filename);
if(f!= null && f.exists())
f.delete();
}
}
=================
在用的时候:将音乐文件以数据流存入
SDcardData localVoice = new SDcardData();
String path1 = Environment.getExternalStorageDirectory().getAbsolutePath();
File file1 = new File(path1 + "/audiorecordtest.mp4");
if(file1.exists()){
FileInputStream fis;
try {
fis = new FileInputStream(file1);
localVoice.writeToSDFromInput(localVoiceId+".MP4", fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(getActivity(), "保存成功", 1).show();
}