首先建立資料夾
final String writeDir= Environment.getExternalStorageDirectory()+ "/YourAppName/log/";
File dir = new File(writeDir);
dir.mkdirs();
case1. 寫入文字檔案
mFileWriter = new FileWriter(writeDir+ "/logFile.txt", true);
mFileWriter.write("yayahihihello");
mFileWriter.flush();
mFileWriter.close();
case2. 使用FileOutputStream儲存圖檔
//這個路徑可以被內建的gallery app 找到
final String writePath = Environment.getExternalStorageDirectory()+"/Pictures/YourAPPName";
Bitmap bitmap = (拿到你要存的bitmap);
//將Bitmap轉成bytes才能儲存
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//使用FileOutputStream儲存bytes
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
bytes.close();
fo.close();
接著最後儲存的檔案編號繼續下去
String fileName,fileNameBase = "CanvasNetPic" ;
int counter =1;
fileName = "CanvasNetPic0";
File f = new File(savePath+"/"+fileName+".jpg");
while(f.exists())
{
fileName = fileNameBase + Integer.toString(counter);
f = new File(savePath+"/"+fileName+".jpg");
counter++;
}
通知Android media scanner file system被改變過, 這樣新儲存的檔案才會馬上被gallery或其他content reader讀到
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
但這樣子media scanner會去重新掃描整個ExternalStroage, 或是檔案很多或是device比較慢的話要掃很久, 會導致打開gallery以後要放著一段時間新儲存的檔案才會出來
只掃描儲存檔案的資料夾可以大幅減掃掃描時間:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ "你的儲存路徑")));
沒有留言:
張貼留言