Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

一個簡單卻容易忽略的 BUG:檔名裡的冒號

編輯:關於 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("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.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
    } catch (Exception e) {
        out.close();
    }
}

// 超過 3 張就刪掉多餘的
public void manageFiles(File dir, String extension) {
    File[] files = dir.listFiles(getFilter(dir, extension));
    if (files.length >= 3) {
        for (int i = 2; i < files.length; i++) {
            files[i].delete();
        }
    }
}

排查過程

運行時不管怎麼試,總是在 new FileOutputStream(path) 這一行丟出異常。我把該檢查的都檢查了一遍:SD 卡權限有申請、目錄用 mkdirs() 建好了、Environment.getExternalStorageDirectory() 回傳的值也正常、除錯過程一路順利沒有其他錯誤訊息。就是找不到原因。

後來靈機一動,回頭盯著日期格式字串看:

SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");

我在電腦桌面上試著建立一個名稱裡帶冒號的文字檔,作業系統直接跳出錯誤——冒號是檔名保留字元,不能用來命名檔案。

對,BUG 就是這個。Android 底層是 Linux 檔案系統,技術上允許冒號出現在檔名中,但上層的 File 與各項系統服務在處理時並不保證一致,於是就在 FileOutputStream 這一步炸了。

修法

把格式字串中的冒號換掉即可,最直白的做法是用時分秒之間不加分隔或改用其他合法字元:

SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");

這樣產生的檔名像 20260826225316.png,排序時也剛好符合時間先後,比原本的 yyyy-MM-dd-hh:mm:ss 更好用。

順手記兩個相關經驗

第一,檔名別用使用者可見的格式直接命名。除了冒號,Windows 相容性上還有 < > : " / \ | ? * 這一組保留字元;Android 上則要特別避開 / because 它會被當成路徑分隔符。若要保留可讀時間,用 yyyyMMdd_HHmmss 這種底線分隔最安全。

第二,那個 catch 區塊本身也有問題。

} catch (Exception e) {
    out.close();   // 若 new FileOutputStream 就失敗,out 仍是 null
}

如果異常發生在 FileOutputStream 建立階段,out 會是 null,此行會再拋一次 NullPointerException,把原本真正的錯誤訊息掩蓋掉。這也是我當初查了那麼久的原因之一——日誌裡根本看不到關鍵資訊。正確做法是在 catch 中 e.printStackTrace(),並把 close 放到 finally 中加 null 判斷。

結論很樸素:檔名只用英數、底線與連字號,是最省事的自我保護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved