跪拜 Guibai
← All articles
Frontend · Android

Android Build Error 'Unable to delete file': Stop the Lock, Clean the Cache, Rebuild

By 90后晨仔 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

A developer whose builds fail on 'Unable to delete file' can confirm whether a locked cache file is the culprit within minutes, and the fix works without touching code or plugin versions.

Summary

Android builds occasionally die with 'Unable to delete file .../file-map.txt' during cache cleanup. The cause is a file handle held by a running process: the Gradle daemon, an IDE's indexing thread, or security software scanning the build directory. The error is not a code or configuration problem.

The fix is a sequence of stops and cleans. Exit any IDE that has the project open, run `./gradlew --stop` to shut down the daemon, remove `app/build` and `.gradle`, then rebuild with `./gradlew clean assembleDebug` or the IDE's Clean Project and Rebuild. If the error persists, `lsof | grep file-map.txt` shows the PID holding the file, and a system restart releases everything.

Prevention is straightforward: don't build from two tools at once, stop the daemon before cleanup, and suspect process locks before touching business code or plugin versions.

Takeaways
— The error 'Unable to delete file .../file-map.txt' occurs when a process holds an open handle to a Gradle cache file.
— Common lock holders: Gradle Daemon, IDE indexing (Android Studio, IntelliJ, VS Code), simultaneous IDE/command-line builds, and security software.
— Run `./gradlew --stop` from the project root to stop the Gradle daemon.
— Delete `app/build` and `.gradle` to clear project-level build caches.
— Rebuild with `./gradlew clean assembleDebug` or the IDE's Clean Project/Rebuild.
— Use `lsof | grep file-map.txt` to identify the PID holding the file; restart the system as a last resort.
— Avoid building from IDE and CLI at the same time; run `./gradlew --stop` before cleanup.
Conclusions

Checking for process locks before modifying code or Gradle configuration prevents hours of debugging a symptom that stems from file ownership, not build logic.

Gradle's daemon, which speeds up builds by staying alive, is a common source of stale file handles; stopping it before cleaning caches is a reliable first move.

Concepts & terms
Gradle Daemon
A long-running JVM process Gradle uses to avoid cold starts; it can hold open file handles on build cache files and cause deletion failures.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗