# Io / Github / Biezhi / Java11 / Files

## Overview

The `io.github.biezhi.java11.files` package is part of the broader Java 11 feature showcase by [biezhi](https://github.com/biezhi). It demonstrates the new convenience methods for reading and writing text files that were added to `java.nio.file.Files` in Java 11. Before this release, developers had to manually open streams, wrap them in readers/writers, and manage resource cleanup — even for simple text file operations. This package provides a minimal, self-contained example showing how `Files.readString()` and `Files.writeString()` drastically simplify common file I/O patterns.

## Package Context

This package sits within a larger set of example modules under `io.github.biezhi.java11`, each exploring a different feature introduced in Java 11:

- [collections](/io/github/biezhi/java11/collections) — Diamond operator improvements
- [http](/io/github/biezhi/java11/http) — New HttpClient API
- [interfaces](/io/github/biezhi/java11/interfaces) — Private methods in interfaces
- [string](/io/github/biezhi/java11/string) — New String methods (`isBlank`, `strip`, `lines`, etc.)
- [time](/io/github/biezhi/java11/time) — Additional time API features
- [trywithresources](/io/github/biezhi/java11/trywithresources) — Try-with-resources patterns
- [var](/io/github/biezhi/java11/var) — Local variable type inference
- [singlefile](/io/github/biezhi/java11/singlefile) — Single-file source execution

The `files` subpackage focuses specifically on the new one-shot file I/O methods.

## Key Classes

### `Example`

**Source:** [src/main/java/io/github/biezhi/java11/files/Example.java](src/main/java/io/github/biezhi/java11/files/Example.java)

The sole class in this package. It serves as a runnable demonstration of the Java 11 `Files` convenience methods for text file operations. The class contains only a `main` method and is designed to be executed directly to verify the new API works as expected.

#### Method: `main(String[] args)`

**Signature:** `public static void main(String[] args) throws Exception`

**Location:** [src/main/java/io/github/biezhi/java11/files/Example.java:14](src/main/java/io/github/biezhi/java11/files/Example.java:14)

This is the entry point and the only method in the package. It demonstrates a complete write-read-delete lifecycle for a text file using Java 11's new API:

1. **Write a string to a file** — Uses `Files.writeString(Paths.get("hello.txt"), text)` to write the text `"Hello biezhi."` to a file. This replaces the boilerplate pattern of opening a `BufferedWriter`, wrapping it in an `OutputStreamWriter`, and manually closing the stream.

2. **Read the string back** — Uses `Files.readString(Paths.get("hello.txt"))` to read the full file content into a `String`. This replaces the pattern of opening a `BufferedReader`, reading line by line into a `StringBuilder`, and manually closing the stream.

3. **Delete the file** — Uses `Files.delete(Paths.get("hello.txt"))` to remove the temporary file. Note that `Files.delete()` was already available in Java 7; it's included here simply as cleanup.

4. **Verify the round-trip** — Prints the result of `text.equals(readText)` to confirm the write and read operations matched. This will output `true`.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `args` | `String[]` | Standard command-line arguments (unused by this method) |

**Returns:** `void`

**Throws:** `Exception` — The method declares a broad `Exception` throw, since `Files.writeString()`, `Files.readString()`, and `Files.delete()` can all throw various `IOException` subtypes (e.g., `NoSuchFileException`, `FileAlreadyExistsException`, `AccessDeniedException`).

#### Flow Diagram

The following diagram shows the operation sequence within the `main` method:

```mermaid
flowchart TD
    A["start: main()"] --> B["Define text = \"Hello biezhi.\""]
    B --> C["Files.writeString() → write to hello.txt"]
    C --> D["Files.readString() → read from hello.txt"]
    D --> E["Compare text == readText"]
    E --> F["Print result (true)"]
    F --> G["Files.delete() → remove hello.txt"]
    G --> H["end"]
```

#### Why These Methods Matter

Before Java 11, equivalent functionality required significantly more code:

**Pre-Java 11 file write:**
```java
Files.write(Paths.get("hello.txt"),
    "Hello biezhi.".getBytes(),
    StandardOpenOption.CREATE);
```

**Pre-Java 11 file read:**
```java
String content = new String(
    Files.readAllBytes(Paths.get("hello.txt")));
```

The Java 11 methods (`Files.writeString()` and `Files.readString()`) are semantically clearer — the method names explicitly indicate string operations rather than byte-level manipulations, and they handle character encoding consistently (always UTF-8).

## How It Works

The module follows a straightforward pattern:

1. Obtain a `Path` object via `Paths.get(String)`, which resolves to a `java.nio.file.Path`.
2. Call the static method on `java.nio.file.Files`, passing the `Path` and the string content.
3. The `Files` methods use UTF-8 encoding by default for both reading and writing.
4. All exceptions propagate as unchecked or broad `Exception` (the method declares `throws Exception` rather than catching specific subtypes).

## Data Model

This package does not define any custom data model classes. The only data flowing through the system is a plain `String`:

| Name | Type | Role |
|------|------|------|
| `text` | `String` | The content written to the file ("Hello biezhi.") |
| `readText` | `String` | The content read back from the file |

## Dependencies and Integration

**External dependencies:** None. The module only uses classes from the Java standard library:

- `java.nio.file.Files` — Core file I/O convenience methods
- `java.nio.file.Paths` — Utility for obtaining `Path` instances

**Module dependencies:** This package does not depend on any other packages in the project, and nothing in the project depends on this package. It is fully self-contained.

## Notes for Developers

- **UTF-8 encoding is assumed.** Both `Files.writeString()` and `Files.readString()` use UTF-8 encoding by default. If you need a different encoding, use the overloaded variants that accept a `Charset` parameter.

- **Full file contents are loaded into memory.** These convenience methods read the entire file at once. For very large files, consider using `Files.lines()` or streaming APIs instead to avoid `OutOfMemoryError`.

- **The class is not designed for reuse.** It contains only a `main` method and no instance state. To use this functionality in real code, invoke the `Files` methods directly rather than instantiating `Example`.

- **File location.** The example uses a relative path `"hello.txt"`, which means the file is created in the current working directory at runtime. The exact location depends on how the application is launched.

- **Exception handling.** The method declares `throws Exception`, which is acceptable for a demo/example class but should not be replicated in production code. Catch or handle specific `IOException` subtypes in real applications.
