Version 1.7
Copyright © 2008 - 2010 Lars Vogel
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 |
Table of Contents
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"));
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 } } } }
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); }
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); } }
You can read resources from your project or
your jar
file via the
.getClass().getResourceAsStream()
method chain
from any object.
Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.