Home Tutorials Training Consulting Products Books Company Donate Contact us

Online Training

Quick links


Java Input Output. This tutorial explains how to read and write files via Java.

1. Java I/O (Input / Output) for files

1.1. Overview

In modern Java applications you typically use the java.nio.file API to read and write files.

Java will read all input as a stream of bytes. The InputStream class is the superclass of all classes representing an input stream of bytes.

1.2. Reading a file in Java

To read a text file you can use the Files.readAllBytes method. The usage of this method is demonstrated in the following listing.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

// somewhere in your code

String content = new String(Files.readAllBytes(Paths.get(fileName)));

To read a text file line by line into a List of type String structure you can use the Files.readAllLines method.

List<String> lines = Files.readAllLines(Paths.get(fileName));

Files.readAllLines uses UTF-8 character encoding. It also ensures that file is closed after all bytes are read or in case an exception occurred.

1.3. Reading and filtering line by line

The Files.lines method allows read a file line by line, offering a stream. This stream can be filtered and mapped. Files.lines does not close the file once its content is read, therefore it should be wrapped inside a try-with-resource statement.

In the following example unnecessary whitespace at the end of each line is removed and empty lines are filterer.

//read all lines and remove whitespace (trim)
//filter empty lines
//and print result to System.out

Files.lines(new File("input.txt").toPath())
    .map(s -> s.trim())
 .filter(s -> !s.isEmpty())

The next example demonstrates how to filter out lines based on a certain regular expression.

Files.lines(new File("input.txt").toPath())
    .map(s -> s.trim())
 .filter(s -> !s.matches("yourregularexpression"))

The next example extracts a line starting with "Bundle-Version:" from a file called "MANIFEST.MF" located in the "META-INF" folder. It removes the prefix and removes all leading and trailing whitespace.

package com.vogella.eclipse.ide.first;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.stream.Stream;

public class ReadMANIFESTFile {
    public static void main(String[] args) throws IOException {
        String versionString = readStreamOfLinesUsingFiles();

    private static String readStreamOfLinesUsingFiles() throws IOException {
        Stream<String> lines = Files.lines(Paths.get("META-INF", "MANIFEST.MF"));
        Optional<String> versionString = lines.filter(s -> s.contains("Bundle-Version:")).map(e-> e.substring(15).trim()).findFirst();

        if (versionString.isPresent())
            return versionString.get();
        return "";

1.4. Writing a file in Java

To write a file you can use the following method:

Files.write(stateFile.toPath(), content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);

1.5. How to identify the current directory

You can access files relative to the current execution directory of your Java program. To access the current directory in which your Java program is running, you can use the following statement.

// writes all files of the current directory

1.6. List all files and sub-directories using Files.list()

String currentDir = System.getProperty("user.dir");

2. Exercise: Reading and writing files

Create a new Java project called com.vogella.java.files. Create the following FilesUtil.java class.

package com.vogella.java.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class FilesUtil {
    public static String readTextFile(String fileName) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get(fileName)));
        return content;

    public static List<String> readTextFileByLines(String fileName) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(fileName));
        return lines;

    public static void writeToTextFile(String fileName, String content) throws IOException {
        Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE);


To test these methods, create a text file called file.txt with some content in your project folder. Create the following Main class and run it.

package com.vogella.java.files;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) throws IOException {
    String input = FilesUtil.readTextFile("file.txt");
    FilesUtil.writeToTextFile("copy.txt", input);


    Path path = Paths.get("file.txt");

3. Exercise: Deleting a directory with all subdictories and files

To delete a directory and all its content.

String stringPath="...yourPath...";
Path path = new File(stringPath).toPath();

4. Reading resources out of your project / jar

You can read resources from your project or your jar file via the .getClass().getResourceAsStream() method chain from any object.

5. About this website

6. Links and Literature

Nothing listed.

6.1. vogella GmbH training and consulting support


The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2018 vogella GmbH. Free use of the software examples is granted under the terms of the Eclipse Public License 2.0. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.