Question
How to Fix Gradle 'Unable to Delete File' in Android Studio Kotlin Projects
Question
I am trying to rebuild an Android Studio Gradle project that contains mostly Kotlin code, but the clean or rebuild process fails with an UnableToDeleteFileException.
The error looks like this:
Execution failed for task ':app:clean'.
> Unable to delete file: C:\Users\User\KotlinGameEngine\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.1\jars\classes.jar
This started after I changed the project's package structure by manually renaming and moving source folders instead of using Android Studio refactoring tools.
I tried all of the following, but the problem still occurs:
- Running a Gradle sync
- Reinstalling the Java JRE and JDK
- Reinstalling Android Studio
- Rolling back Android Studio versions
- Invalidating caches and restarting
- Deleting the project's
gradleand.gradledirectories - Deleting the user-level
.gradledirectory - Running
gradlew clean - Copying the source files into a new project
The only temporary workarounds were:
- Closing Android Studio, manually deleting the
buildfiles, and reopening it - Killing the
java.exeprocess while Android Studio is running
That makes it seem like a Java process is holding a lock on generated build files. I also noticed the issue appears only in the Kotlin-based Android project, not in a Java-only Android project.
Later testing suggested that the issue appeared whenever the project contained Kotlin files, and the lock remained until the background Java process was killed.
What is happening when Gradle says it cannot delete a file, and how should I diagnose and fix this kind of file-lock problem in an Android Studio or Kotlin Gradle project?
Short Answer
By the end of this page, you will understand what Gradle's Unable to delete file error usually means, why it often points to a file lock rather than a missing file, and how to diagnose the process that is holding the lock in Android Studio or Kotlin-based Android projects. You will also learn practical cleanup steps, safer project refactoring habits, and a repeatable troubleshooting workflow.
Concept
When Gradle runs tasks like clean, rebuild, or dependency extraction, it creates and deletes many generated files inside directories such as build/, .gradle/, and intermediate cache folders.
If Gradle says it is unable to delete a file, the problem usually is not that the file does not exist. It usually means one of these things:
- Another process is still using the file
- The operating system has locked the file
- A background compiler, indexer, antivirus, or IDE process is scanning it
- A Gradle daemon or plugin has not released a handle to the file
- Permissions or read-only attributes prevent deletion
In Windows, file locking is especially visible because a process can hold an exclusive handle that prevents deletion until that process exits or releases the file.
In Android projects, this often happens around:
- Gradle daemons
- Kotlin compilation processes
- Android Studio indexing
- ADB or packaging tools
- Antivirus or backup tools watching the project folder
Why this matters:
- Build failures slow down development
- Stale generated files can cause confusing errors
- Killing processes blindly may hide the real cause
- Understanding file locks helps you debug IDE, Gradle, and plugin issues more systematically
The key idea is this: the error is usually a symptom of resource locking, not a syntax problem in your Kotlin code.
Mental Model
Think of your project files like tools on a workbench.
- Gradle is the worker cleaning up the bench
- Android Studio and the Kotlin compiler are other workers using the same tools
- If one worker is still gripping a tool, Gradle cannot put it away
So Unable to delete file means:
"I tried to clean up this file, but some other process is still holding it."
This is why deleting build/ manually sometimes works only once: the process releases the file temporarily, then grabs it again during the next build.
A good mental model is:
- Compilation creates files
- Background tools watch files
- Clean tries to remove files
- Locks cause conflict
Syntax and Examples
The core concept here is not a Kotlin syntax feature but a build troubleshooting pattern: identify the locked file, identify the process holding it, stop or reconfigure that process, then rebuild.
Typical Gradle error
Execution failed for task ':app:clean'.
> Unable to delete file: C:\path\to\project\app\build\intermediates\...\classes.jar
Typical cleanup commands
On Windows:
gradlew --stop
gradlew clean
If that does not work, close Android Studio first, then run:
rmdir /s /q app\build
rmdir /s /q .gradle
On macOS/Linux, the equivalent would be:
./gradlew --stop
./gradlew clean
rm -rf app/build .gradle
Example: safer troubleshooting sequence
gradlew --stop
gradlew clean --info
What this does:
--stopstops Gradle daemons that may still hold file handlescleanremoves generated build output--infoprints more details that can help confirm where the failure happens
Example: what to inspect
Step by Step Execution
Consider this simplified workflow:
1. Gradle builds the app
2. Kotlin compiler creates or updates generated artifacts
3. Android Studio or a daemon keeps a handle open
4. Gradle runs clean
5. Windows blocks deletion because the file is still in use
Traceable example
Imagine Gradle wants to delete:
app\build\intermediates\example\classes.jar
Step by step:
-
Build starts
- Gradle resolves dependencies
- Kotlin and Java compilation run
classes.jaris created or updated
-
Background process stays alive
- A Java or Kotlin daemon continues running after compilation
- It still has access to that JAR file
-
You trigger Rebuild or Clean
- Gradle tries to remove the old
build/contents
- Gradle tries to remove the old
-
Deletion fails
- Windows sees that another process is using
classes.jar - Gradle throws an error like:
- Windows sees that another process is using
Unable to delete file
- You kill the process
Real World Use Cases
This concept appears in many real development environments, not just Android Studio.
Android app development
build/outputs cannot be removed duringclean- Generated APK or AAR files remain locked
- Kotlin or Java compiler daemons keep files open
Backend services
- JAR files cannot be replaced during deployment because a Java process still uses them
- Log files cannot be rotated because a running service has them open
Frontend tooling
- Bundlers watch output files
- Dev servers lock generated artifacts during rebuilds
CI/CD pipelines
- A previous build step did not terminate properly
- Cached workspaces contain locked or read-only files
- Parallel jobs conflict over the same output directory
Scripts and automation
- A cleanup script fails because another script is still reading a file
- Temporary files remain open due to missing resource cleanup
The broad lesson: build systems are not only about code compilation; they also depend on correct file lifecycle management.
Real Codebase Usage
In real projects, developers handle this kind of issue with repeatable debugging and safer workflows.
Common patterns developers use
Guarded cleanup steps
Before deleting outputs, teams often stop background processes first:
gradlew --stop
This is a guard clause for build cleanup: stop daemons before removing files.
Early isolation of the cause
Developers try to answer:
- Is the lock caused by Gradle?
- Is it caused by the IDE?
- Is it caused by a plugin?
- Is it caused by antivirus or indexing?
A common pattern is to test outside the IDE:
gradlew clean build
If the command line works but Android Studio fails, the IDE is likely involved.
Validation after structural refactors
When renaming packages or moving source roots, real teams prefer IDE refactoring tools because they update:
- package declarations
- imports
- build references
- generated metadata
Manual folder moves can leave stale generated files behind.
Error handling through clean-room rebuilds
A common recovery pattern is:
- Close the IDE
- Stop Gradle daemons
- Remove
build/and.gradle/caches where appropriate
Common Mistakes
1. Assuming the file itself is broken
A file deletion error usually does not mean the JAR contents are invalid.
Broken assumption:
Gradle cannot delete classes.jar, so classes.jar must be corrupted.
More likely:
Another process is still using classes.jar.
2. Reinstalling tools before checking file locks
Reinstalling Java or Android Studio is often much slower than checking whether a process is holding the file.
A better order is:
- Stop Gradle daemons
- Close the IDE
- Find the locking process
- Clean caches only if needed
3. Manually moving packages instead of refactoring
This can leave the project in an inconsistent state.
Risky approach:
Rename package folders in the file system directly
Safer approach:
- Use Android Studio refactor tools
- Then run a clean rebuild
4. Deleting random cache folders repeatedly
This may temporarily hide the issue without identifying the real cause.
5. Ignoring external tools
The lock may come from:
- antivirus
- backup sync clients
- file indexers
- preview tools
6. Confusing correlation with cause
Comparisons
| Situation | What it usually means | Best next step |
|---|---|---|
Unable to delete file | A process is using the file, or permissions prevent deletion | Check for file locks, stop daemons, close the IDE |
File not found | The path does not exist | Check path correctness and build task order |
Permission denied | Access rights are insufficient | Run with proper permissions, inspect file attributes |
Compilation failed | Source code or configuration problem | Fix code, dependencies, or compiler settings |
| Approach | Pros | Cons |
|---|---|---|
| Kill manually |
Cheat Sheet
Gradle 'Unable to delete file' usually means:
- file lock
- open process handle
- permission problem
- antivirus/indexer interference
First things to try
gradlew --stop
gradlew clean --info
Then:
- Close Android Studio
- Delete
app/build/ - Delete project
.gradle/if needed - Reopen and rebuild
Common causes
- Gradle daemon
- Kotlin compiler daemon
- Android Studio indexing
- Antivirus
- File sync tools
- Read-only files
Good debugging order
- Reproduce the error
- Note the exact file path
- Stop Gradle daemons
- Close the IDE
- Try deleting the file manually
- If deletion fails, find the locking process
- Update or reconfigure the tool causing the lock
Useful commands
gradlew --stop
gradlew clean
gradlew build --info
Safer refactoring rule
- Use IDE refactoring for package renames and moves
- Avoid manual filesystem-only package changes in Android projects
Edge cases
- The file may be read-only
- Path length issues can matter on Windows
FAQ
Why does Gradle say it cannot delete a file during clean?
Usually because another process still has the file open, so the operating system refuses to delete it.
Is this a Kotlin code error?
Usually no. If Kotlin is involved, the issue is more likely related to the Kotlin compiler process, plugin behavior, or generated build artifacts.
Why does killing java.exe temporarily fix the problem?
Because that process may be holding the file handle. When it stops, Windows releases the lock.
Should I delete the build folder manually?
Yes, as a temporary cleanup step, but it is better to also identify what process is locking the files.
Does Android Studio package refactoring matter here?
Yes. Refactoring through the IDE is safer because it updates related project metadata and reduces stale build state.
How do I find which process is locking the file on Windows?
Use tools like Resource Monitor or Process Explorer and search for the file path or filename.
Why does the issue seem to persist even in a new project?
Because the locking process may be external to the project itself, such as a background Java process, Gradle daemon, IDE process, or system utility.
Should I reinstall Android Studio or Java first?
Usually no. Start with process-lock diagnostics, daemon shutdown, and build directory cleanup before reinstalling tools.
Mini Project
Description
Create a small troubleshooting checklist script and workflow for an Android or Gradle project that fails during clean because a build file is locked. This project helps you practice systematic diagnosis instead of repeatedly deleting folders by hand.
Goal
Build a repeatable cleanup process that stops daemons, removes generated files, and guides you to identify file-lock problems safely.
Requirements
- Create a script that stops Gradle daemons.
- Make the script remove the project's
builddirectory. - Print a message reminding the user to close Android Studio first.
- Print a message explaining that a locked file may require checking running Java processes.
- Keep the script simple and runnable from the project root.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Allow HTTP and HTTPS in Android 9 Pie with Network Security Configuration
Learn how Android 9 Pie handles cleartext HTTP traffic and how to allow HTTP and HTTPS safely using network security config.
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.