Java Tutorial

Java Files

Files.readString and Files.writeString read and write text through a Path. Always handle IOException — the disk can fail.

Path plus Files

Modern Java file I/O lives in java.nio.file. A Path names a location;Files.writeString writes text and Files.readString reads it back. Both throw checked IOException, so main must catch it or declare throws.

Example

import java.nio.file.*;

public class Main {
  public static void main(String[] args) throws Exception {
    Path path = Path.of("note.txt");
    Files.writeString(path, "Ada 2026");
    System.out.println(Files.readString(path));
  }
}

The StudyGrid browser editor runs in a sandbox. These examples compile and show the API, but a real disk write may be blocked. Download the .java file and run it locally when you need files on disk.

Append and check existence

Pass StandardOpenOption.APPEND to add to an existing file. Use Files.exists before you assume a path is there.

Example

import java.nio.file.*;

public class Main {
  public static void main(String[] args) throws Exception {
    Path path = Path.of("log.txt");
    Files.writeString(path, "line1\n");
    Files.writeString(path, "line2\n", StandardOpenOption.APPEND);
    System.out.println(Files.exists(path));   // true
    System.out.println(Files.readString(path));
  }
}

try-with-resources for streams

For line-by-line reading, open a BufferedReader with try-with-resources so the file closes even if an error occurs. The GC frees memory; it does not close file handles for you.

Example

import java.io.BufferedReader;
import java.nio.file.*;

public class Main {
  public static void main(String[] args) throws Exception {
    Path path = Path.of("note.txt");
    Files.writeString(path, "one\ntwo\nthree\n");
    try (BufferedReader br = Files.newBufferedReader(path)) {
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }
    }
  }
}

Catch IOException

Declaring throws Exception on main is fine for small demos. In real programs, catch near the I/O and show a clear message.

Example

import java.io.IOException;
import java.nio.file.*;

public class Main {
  public static void main(String[] args) {
    try {
      String text = Files.readString(Path.of("missing.txt"));
      System.out.println(text);
    } catch (IOException e) {
      System.out.println("Could not read: " + e.getMessage());
    }
  }
}

Prefer Path.of(...) and Files.* over older File +FileWriter for new code — the NIO API is clearer and works better with modern options.

Try It Yourself

Exercise: Write your name to hello.txt with Files.writeString, then read it back and print it. Handle errors with throws Exception on main.

Show solution
import java.nio.file.*;

public class Main {
  public static void main(String[] args) throws Exception {
    Path path = Path.of("hello.txt");
    Files.writeString(path, "StudyGrid");
    System.out.println(Files.readString(path));
  }
}

writeString creates or overwrites the file; readString returns the full text as one String.

Key Takeaways

  • Path names a file; Files.readString / writeString handle whole-file text.
  • IOException is checked — catch it or declare throws.
  • Use try-with-resources for readers/writers so handles close reliably.
  • Browser sandboxes may block disk I/O; run file demos locally when you need real writes.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Statistics

Count lines of data

A text dump of readings is one line per sample. Counting lines is the first size check before you parse numbers.

Example

public class Main {
  public static void main(String[] args) {
    String text = "12.1\\n12.3\\n12.0";
    System.out.println(text.lines().count());
  }
}

Engineering

Split a CSV row

Log files are often comma-separated. split turns one line into fields you can index.

Example

public class Main {
  public static void main(String[] args) {
    String row = "t,12.4,C";
    String[] parts = row.split(",");
    System.out.println(parts[1]);
  }
}

FAQ: Java Files

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java files examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java files in this Java Java lesson (Java Files).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.