Example of writing a file

    
try (PrintWriter printWriter = new PrintWriter ("example.txt"))
{
    printWriter.println ("Hello!");
    printWriter.println ("Goodbye!");
}
catch (IOException e) 
{
    System.err.println("Error writing file: " + e.getMessage());
}
    

Example of appending at the end of file

    
PrintWriter printWriter = null;
try 
{
    printWriter = new PrintWriter(new BufferedWriter(
        new FileWriter("example.txt", true)));
    printWriter.println ("Hello again!");
    printWriter.println ("Goodbye!");
}
catch (IOException e) 
{
    System.err.println("Error writing file: " + e.getMessage());
}
finally 
{
    if (printWriter != null)  
    {
        printWriter.close();
    }
}
    

Example of reading a file

    
try (BufferedReader inputFile = new BufferedReader(
        new FileReader(new File("example.txt"))))
{

    String line = null;
    while ((line = inputFile.readLine()) != null) 
    {
        System.out.println(line);
    }
}
catch (IOException fileError) 
{
    System.err.println(
        "Error reading file: " +
        fileError.getMessage() );
}
    

Example of extending a reader

    
public class UpperCaseReader extends BufferedReader 
{
    public UpperCaseReader(Reader reader) 
    {
        super(reader);
    }

    @Override
    public String readLine() throws IOException 
    {
        String line = super.readLine();
        return line != null?line.toUpperCase():null;    
    }
}

// Main
try(UpperCaseReader buffer = 
    new UpperCaseReader(new FileReader("file.txt"))) 
{
    String line;
    while((line = buffer.readLine()) != null) 
    {
        System.out.println(line);
    }
} catch ...
    

Example: copying a file

    
try
{
    if (!Files.exists(Paths.get("copy")))
        Files.createDirectory(Paths.get("copy"));

    Files.copy(Paths.get("data/file.txt"), 
        Paths.get("copy/file.txt"),
        StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException e)
{
    ...
}
    

Serialization example

    
class Person implements Serializable
{
    private String name;
    private int age;

    ...
}
    

Writing example

    
try(ObjectOutputStream oos =
    new ObjectOutputStream(new FileOutputStream("people.dat")))
{
    oos.writeObject(new Person("John", 49));
    oos.writeObject(new Person("Susan", 45));
}
catch (IOException e)
{
    System.err.println("Error storing people");
}
    

Reading example

    
try(ObjectInputStream ois =
    new ObjectInputStream(new FileInputStream("people.dat")))
{
    while(true)
    {
        Person p = (Person)(ois.readObject());
        System.out.println(p);
    }
}
catch (Exception e)
{
    System.err.println("Error storing people");
}