gradle/gradle · error · UncheckedIOException

Could not write to file '%s'.

Error message

Could not write to file '%s'.

What it means

Non-FileSystemException IO failures while writing a text file through IoActions are wrapped as UncheckedIOException("Could not write to file '%s'."). The cause holds the real IOException - stream failures, encoding problems, or generic I/O errors that the filesystem-reason branch did not classify.

Source

Thrown at platforms/core-runtime/base-services/src/main/java/org/gradle/internal/IoActions.java:152

            this.encoding = encoding;
        }

        @Override
        public void execute(Action<? super BufferedWriter> action) {
            try {
                File parentFile = file.getParentFile();
                if (parentFile != null) {
                    if (!parentFile.mkdirs() && !parentFile.isDirectory()) {
                        throw new IOException(String.format("Unable to create directory '%s'", parentFile));
                    }
                }
                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(file.toPath()), encoding))) {
                    action.execute(writer);
                }
            } catch (FileSystemException e) {
                throw new UncheckedIOException(String.format("%s: '%s'.", e.getReason(), file), e);
            } catch (IOException e) {
                throw new UncheckedIOException(String.format("Could not write to file '%s'.", file), e);
            }
        }
    }

}

View on GitHub (pinned to 534f27719b)

Solutions

  1. Inspect the cause IOException - it carries the actual reason the write failed
  2. If the file sits on a network mount, check connectivity and remount
  3. Verify the configured encoding string is a valid charset name
Defensive patterns

Strategy: try-catch

Try / catch

try {
    IoActions.writeTextFile(targetFile, charsetName).execute(action);
} catch (UncheckedIOException e) {
    if (e.getMessage() != null && e.getMessage().startsWith("Could not write to file")) {
        IOException cause = (IOException) e.getCause(); // real reason lives here
        // handle/retry on the specific IOException
    }
    throw e;
}

Prevention

When it happens

Trigger: The action executed against the BufferedWriter throws a plain IOException, or the stream fails mid-write in a way that is not a FileSystemException - the second catch branch wraps it with the target file path.

Common situations: Writer actions throwing checked exceptions, broken pipes when the consumer of the stream died, or network-mounted filesystems returning generic IO errors.

Related errors


AI-assisted analysis of gradle/gradle@534f27719b (2026-08-22). Data as JSON: /api/errors/c62a546b0d553a5d. Report an issue: GitHub.