Skip to content

Files.newBufferedWriter() takes a Path object, but incorrectly passed a File object #271

Description

@authentictech

In Tutorials > The Java I/O API > File Operations Basics > Releasing Resources and Catching Exceptions, "Catching Exceptions" section, the sample code creates a File object and passes it into Files.newBufferedWriter().

However, according to the Java Docs, this method takes a java.nio.file.Path object, not a java.io.File object.

Charset charset = Charset.forName("US-ASCII");
File file = ...;
String s = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
    writer.write(s, 0, s.length());
} catch (IOException x) {
    System.err.format("IOException: %s%n", x);
}

Activity

  1. authentictech commented on Aug 13, 2026

    @authentictech
    Author

    Same is true for the second sample code:

    Charset charset = Charset.forName("US-ASCII");
    File file = ...;
    String s = ...;
    BufferedWriter writer = null;
    try {
        writer = Files.newBufferedWriter(file, charset);
        writer.write(s, 0, s.length());
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    } finally {
        try{
            if (writer != null)
                writer.close();
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }
    
  2. authentictech commented on Aug 15, 2026

    @authentictech
    Author

    Same issue on Tutorials > The Java I/O API > File Operations Basics > Reading and Writing Text Files, section Writing a Text File by Using Buffered Stream I/O

    Charset charset = Charset.forName("US-ASCII");
    File file = ...;
    String s = ...;
    try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
        writer.write(s, 0, s.length());
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions