I need to be able to save a file to the external storgage temp dir. The file I am saving though is the R.raw directory of my app.
I have used this example here.
Move Raw file to SD card in Android
The issue is
1. The app seems to read the .m4a file I want (possible reads the bytes wrong here).
2. When the file is saved to the /tmp dir the file size is totally wrong.
eg one file goes from 30kb to 300kb, another goes from 25kb, to .25kb.
Any suggestions
public String saveAs(int ressound, String whipName){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("saveas", "did not save1");
//return false;
}
String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/tmp/.pw2";
String filename="/"+whipName+".m4a";
Log.i("path", "file path is " + path);
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.i("saveas", "did not save2");
//return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("saveas", "did not save3");
//return false;
}
File k = new File(path, filename);
return k.getAbsolutePath();
}
You CAN read a file in one full buffer like you’re doing, but this is generally bad practice, unless you know the files are small, and the InputStream will know the full size in advance and be able to load all data at once.
If you aren’t absolutely sure of max file size, especially on mobile, don’t try to load the full thing in memory.
See IOUtils code for the classic example:
http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/1.4/org/apache/commons/io/IOUtils.java#IOUtils.copyLarge%28java.io.InputStream%2Cjava.io.OutputStream%29
Also, make sure to close your buffers explicitly.