在我用Android開發一個數獨遊戲的時候,需要添加相關的截屏功能(也就是將玩數獨的界面截下來)
代碼如下:
try{
Bitmap map = Bitmap.createBitmap(
puzzleView.getDrawingCache());
saveBitmap(map);
Toast.makeText(this, R.string.screenshot_success, Toast.LENGTH_SHORT).show();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(this, R.string.screenshot_fail, Toast.LENGTH_SHORT).show();
}
public void saveBitmap(Bitmap bitmap) throws Exception{
String dirPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "MySudoku" +
File.separator + getString(R.string.diff_1 + diff);
File file = new File(dirPath);
if(!file.exists())
file.mkdirs();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");// 最開始用的是yyyy-MM-dd-hh:mm:ss
String date = sDateFormat.format(new java.util.Date());
String path = dirPath + File.separator + date + ".png";
manageFiles(file, ".png");
FileOutputStream out = null;
try{
out = new FileOutputStream(path);
//將bitmap存儲爲png格式的圖片
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
}catch(Exception e){
out.close();
}
}
// 當png格式的圖片超過3個就刪除多餘的png圖片
public void manageFiles(File dir, String extension){
File[] files = dir.listFiles(getFilter(dir, extension));
Log.d(TAG, "There are " + files.length + " pictures");
if(files.length >= 3){
for(int i = 2; i < files.length; i++){
files[i].delete();
}
}
}
可是運行的時候不管怎麼樣,總是會在out = new FileOutputStream(path);報異常
可是就是找不到原因,該檢查的都檢查了,調試過程也很順利,可就是報異常
最後突然發現我創建的
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
嘗試着在電腦上桌面上創建一個類似的txt文件,最後總算讓我找到BUG的所在了
對,其實BUG就是因爲我在創建文件名的時候中間用了:這個在我的電腦上驗證了
最後總算解決了BUG