Support free tutorials:











vogella training Training Books



Java IO (Input Output) (Files) - Tutorial

Lars Vogel

Version 1.7

05.06.2012

Revision History
Revision 0.1 07.08.2008 Lars
Vogel
created
Revision 0.2 - 1.7 22.09.2008 - 05.06.2012 Lars
Vogel
bug fixes and updates

Java Input Output

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


Table of Contents

1. Java I/O (Input / Output) for files
1.1. Overview
1.2. File Access Examples
1.3. Create a file including the directories for a given path
2. Tutorial: Reading and writing files
3. Reading resources out of your project / jar
4. Support free vogella tutorials
4.1. Thank you
4.2. Questions and Discussion
5. Links and Literature

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

1.1. Overview

Java provides a standard way of reading from and writing to files. The java.io package contains classes which can be used to read and write files and other sources.

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.

Classes from the java.io package can be chained, e.g. certain classes handle the reading and writing of an input stream of bytes while others provide a higher level of abstraction, e.g. to read a line of a file.

In general the classes in this package can be divided into the following classes:

  • Connection Streams: represent connections to destinations and sources such as files or network sockets. Usually low-level.

  • Chain Streams: work only if chained to another stream. Usually higher level protocol, for example they provide the functionality to read a full line of a text file.

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

System.out.println(System.getProperty("user.dir")); 

1.2. File Access Examples

To read a text file you can use the following method:

public String readTextFile(String fileName) {
  
  String returnValue = "";
  FileReader file = null;
  
  try {
    file = new FileReader(fileName);
    BufferedReader reader = new BufferedReader(file);
    String line = "";
    while ((line = reader.readLine()) != null) {
      returnValue += line + "\n";
    }
  } catch (Exception e) {
      throw new RuntimeException(e);
  } finally {
    if (file != null) {
      try {
        file.close();
      } catch (IOException e) {
        // Ignore issues during closing 
      }
    }
  }
  return returnValue;
} 

To write a file you can use the following method:

public void writeTextFile(String fileName, String s) {
    FileWriter output = null;
    try {
      output = new FileWriter(fileName);
      BufferedWriter writer = new BufferedWriter(output);
      writer.write(s);
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (IOException e) {
          // Ignore issues during closing
        }
      }
    }

  } 

1.3. Create a file including the directories for a given path

You can also create the directories automatically for a given file path. The following code shows an example.

File file = new File("foo/bar/test.txt");
File parent = file.getParentFile();

if(!parent.exists() && !parent.mkdirs()){
    throw new IllegalStateException("Couldn't create dir: " + parent);
} 

2. Tutorial: Reading and writing files

Create a new Java project called de.vogella.java.io. Create the following MyFile class.

package de.vogella.java.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MyFile {

  public String readTextFile(String fileName) {
    String returnValue = "";
    FileReader file = null;
    String line = "";
    try {
      file = new FileReader(fileName);
      BufferedReader reader = new BufferedReader(file);
      while ((line = reader.readLine()) != null) {
        returnValue += line + "\n";
      }
    } catch (FileNotFoundException e) {
      throw new RuntimeException("File not found");
    } catch (IOException e) {
      throw new RuntimeException("IO Error occured");
    } finally {
      if (file != null) {
        try {
          file.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return returnValue;
  }

  public void writeTextFile(String fileName, String s) {
    FileWriter output = null;
    try {
      output = new FileWriter(fileName);
      BufferedWriter writer = new BufferedWriter(output);
      writer.write(s);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

  }
} 

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

package de.vogella.java.io;

public class Main {
  public static void main(String[] args) {
    MyFile myFile = new MyFile();
    String input = myFile.readTextFile("Testing.txt");
    System.out.println(input);
    myFile.writeTextFile("Testing2.txt", input);
  }
} 

3. 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.

4. Support free vogella tutorials

Maintaining high quality free online tutorials is a lot of work. Please support free tutorials by donating or by reporting typos and factual errors.

4.1. Thank you

Please consider a contribution if this article helped you.

Flattr this

4.2. Questions and Discussion

If you find errors in this tutorial, please notify me (see the top of the page). Please note that due to the high volume of feedback I receive, I cannot answer questions to your implementation. Ensure you have read the vogella FAQ as I don't respond to questions already answered there.

5. Links and Literature

http://java.sun.com/docs/codeconv/index.html - Sun Coding Convention.