在我用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