Question

How to Fix Gradle 'Unable to Delete File' in Android Studio Kotlin Projects

kotlinandroidandroid-studioandroid-gradle-pluginkotlin-android-extensions

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 gradle and .gradle directories
  • Deleting the user-level .gradle directory
  • Running gradlew clean
  • Copying the source files into a new project

The only temporary workarounds were:

  • Closing Android Studio, manually deleting the build files, and reopening it
  • Killing the java.exe process 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
Take Quiz

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:

  • --stop stops Gradle daemons that may still hold file handles
  • clean removes generated build output
  • --info prints more details that can help confirm where the failure happens

Example: what to inspect

If this file cannot be deleted:

app\build\intermediates\...\classes.jar

Check whether it is being used by:

  • Android Studio
  • Kotlin compiler daemon
  • Java process
  • Antivirus
  • File indexing tool

In practice, developers often use system tools such as:

  • Task Manager to stop suspicious Java processes
  • Resource Monitor or Process Explorer on Windows to find file handles
  • lsof on macOS/Linux

Why the Kotlin plugin seemed related

If adding Kotlin files starts the problem, that does not always mean Kotlin source code is wrong. It can mean:

  • The Kotlin compiler daemon started
  • A plugin created or touched generated files
  • A background process failed to release a file handle

So the right lesson is: when a build tool fails to delete a file, investigate process locking first.

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:

  1. Build starts

    • Gradle resolves dependencies
    • Kotlin and Java compilation run
    • classes.jar is created or updated
  2. Background process stays alive

    • A Java or Kotlin daemon continues running after compilation
    • It still has access to that JAR file
  3. You trigger Rebuild or Clean

    • Gradle tries to remove the old build/ contents
  4. Deletion fails

    • Windows sees that another process is using classes.jar
    • Gradle throws an error like:
Unable to delete file
  1. You kill the process
    • The file handle is released
    • Gradle can delete the file again

Important takeaway

The build is not necessarily failing because the file is corrupted. It is failing because the file is busy.

A practical diagnostic sequence

  1. Close Android Studio
  2. Run:
gradlew --stop
  1. Delete build folders manually
  2. Reopen the project
  3. Build again
  4. If it fails again, identify the process locking the file

This sequence helps distinguish between:

  • stale cache problems
  • plugin bugs
  • IDE indexing issues
  • operating system file locks

Real World Use Cases

This concept appears in many real development environments, not just Android Studio.

Android app development

  • build/ outputs cannot be removed during clean
  • 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.

Take Quiz

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:

  1. Close the IDE
  2. Stop Gradle daemons
  3. Remove build/ and .gradle/ caches where appropriate
  4. Reimport the project
  5. Rebuild from scratch

Process inspection tools

Developers frequently use:

  • Process Explorer on Windows
  • Resource Monitor on Windows
  • lsof on Unix-like systems

These tools are part of real debugging workflows when build tools report deletion failures.

Environment-based fixes

In larger codebases, teams may also:

  • exclude project folders from antivirus scanning
  • shorten long Windows paths
  • avoid syncing build folders with cloud storage tools
  • update Gradle, Kotlin plugin, or Android Gradle Plugin versions if a lock bug is known

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:

  1. Stop Gradle daemons
  2. Close the IDE
  3. Find the locking process
  4. 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

Example:

The issue appears when I add a Kotlin file, so Kotlin code must be wrong.

That may be false. The real cause may be the Kotlin compiler process or plugin lifecycle, not the source code itself.

7. Forgetting that Windows locking rules are stricter

A build that seems fine on one machine may fail on Windows because file handles are enforced more strictly.

Broken vs better example

Broken troubleshooting approach:

# repeatedly try the same command without stopping daemons
gradlew clean
gradlew clean
gradlew clean

Better approach:

gradlew --stop
gradlew clean --info

Then inspect the locking process if it still fails.

Comparisons

SituationWhat it usually meansBest next step
Unable to delete fileA process is using the file, or permissions prevent deletionCheck for file locks, stop daemons, close the IDE
File not foundThe path does not existCheck path correctness and build task order
Permission deniedAccess rights are insufficientRun with proper permissions, inspect file attributes
Compilation failedSource code or configuration problemFix code, dependencies, or compiler settings
ApproachProsCons
Kill java.exe manuallyFast temporary workaroundNot reliable, interrupts development
Delete build/ manuallySometimes worksDoes not fix the underlying lock
gradlew --stopSafe first stepMay not help if a non-Gradle process holds the lock
Reinstall Android StudioOccasionally usefulUsually excessive for a file lock issue
Use Process Explorer / Resource MonitorIdentifies the real locking processRequires an extra diagnostic step
Package change methodResult
Manual folder renameCan leave stale references or generated artifacts
IDE refactorUpdates project structure more safely
Take Quiz

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

  1. Reproduce the error
  2. Note the exact file path
  3. Stop Gradle daemons
  4. Close the IDE
  5. Try deleting the file manually
  6. If deletion fails, find the locking process
  7. 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
  • A plugin bug can hold file handles unexpectedly
  • The problem may continue until the daemon process exits

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.

Take Quiz

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

  1. Create a script that stops Gradle daemons.
  2. Make the script remove the project's build directory.
  3. Print a message reminding the user to close Android Studio first.
  4. Print a message explaining that a locked file may require checking running Java processes.
  5. Keep the script simple and runnable from the project root.
Take Quiz

Keep learning

Related questions

View more