Site Search:

I/O Code Examples

Back>

FileReader
BufferedReader
FileWriter
BufferedWriter
PrintWriter
FileInputStream
BufferedInputStream
ObjectInputStream
FileOutputStream
BufferedOuputStream
ObjectOutputStream
FileInputStream Example code. read(), read(byte[]), markSupported(), skip(int)
cat ReadData.java
import java.io.*;
import java.nio.charset.*;

public class ReadData {
    public static void main(String[] args) {
        try(FileInputStream isr = new FileInputStream("test.txt");) {
            int data = 0;
            byte[] buf = new byte[5];
            System.out.println(isr.markSupported());
            isr.skip(2);
            isr.read(buf);
            String str = new String(buf, StandardCharsets.UTF_8);
            System.out.println(str); 
            while( (data = isr.read()) != -1) {
                System.out.print((char)data);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
cat test.txt 
abcde123456
javac ReadData.java 
java ReadData
false
cde12
3456
chmod -r test.txt 
java ReadData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(FileInputStream.java:138)
 at java.io.FileInputStream.(FileInputStream.java:93)
 at ReadData.main(ReadData.java:6)
chmod +r test.txt 
java ReadData
false
cde12
3456
BufferedInputStream code example: read(), read(byte[]), markSupported(), mark(), reset(), skip().
cat ReadData.java 
import java.io.*;
import java.nio.charset.*;
public class ReadData {
    public static void main(String[] args) {
        try(BufferedInputStream in = new BufferedInputStream(new FileInputStream("test.txt"))) {
            System.out.println(in.markSupported());
            in.mark(10);
            System.out.print((char)in.read());
            byte[] buf = new byte[2];
            in.read(buf);
            System.out.println(new String(buf)); 
            in.reset();
            in.skip(1);
            int lengthRead = 0;
            while((lengthRead = in.read(buf)) > 0) {
                System.out.print(new String(buf, 0, lengthRead, StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
cat test.txt 
abcdefghijk
123456789
javac ReadData.java 
java ReadData
true
abc
bcdefghijk
123456789
chmod -r test.txt 
java ReadData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(FileInputStream.java:138)
 at java.io.FileInputStream.(FileInputStream.java:93)
 at ReadData.main(ReadData.java:5)
chmod +r test.txt 
java ReadData
true
abc
bcdefghijk
123456789

FileOutputStream Example. write(int), write(byte[])
cat WriteData.java
import java.io.*;
import java.nio.charset.*;
public class WriteData
{
  public static void main(String args[]) throws FileNotFoundException
  {
    try(FileOutputStream fos = new FileOutputStream("test.txt");) {
        fos.write('A');
        byte[] buf = new byte[]{'B', 66};
        fos.write(buf, 0, buf.length);
        String hello = "hello OCPJP!";
        fos.write(hello.getBytes(StandardCharsets.UTF_8));
        //one byte at a time, no need to flush
        //fos.flush();
        //try with resources, no need to close
        //fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
  }
}

javac WriteData.java 
java WriteData
cat test.txt 
ABBhello OCPJP!
java WriteData
cat test.txt 
ABBhello OCPJP!
vi WriteData.java
chmod -w test.txt 
java WriteData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:213)
 at java.io.FileOutputStream.(FileOutputStream.java:101)
 at WriteData.main(WriteData.java:7)
rm test.txt 
override r--r--r--  homenetwork/staff for test.txt? y
java WriteData
cat test.txt 
ABBhello OCPJP!
vi WriteData.java 
grep test.txt WriteData.java 
    try(FileOutputStream fos = new FileOutputStream("test.txt",true);) {
echo "appened set to true"
appened set to true
javac WriteData.java
java WriteData
cat test.txt 
ABBhello OCPJP!ABBhello OCPJP!
java WriteData
cat test.txt 
ABBhello OCPJP!ABBhello OCPJP!ABBhello OCPJP!
BufferedOutputStream code example, write(int), write(byte[]), write(byte[], int, int), flush().
cat WriteData.java 
import java.io.*;
public class WriteData
{
  public static void main(String args[]) throws FileNotFoundException
  {
    try(BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("test.txt"))) {
        out.write('A');
        byte[] buf = new byte[]{'B', 66, '6'};
        out.write(buf, 0, buf.length);
        out.write(buf);
        out.flush();  //need to flush
        //try with resources, no need to close
        //out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
  }
}
javac WriteData.java 
java WriteData
cat test.txt 
ABB6BB6

chmod -w test.txt 
java WriteData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:213)
 at java.io.FileOutputStream.(FileOutputStream.java:101)
 at WriteData.main(WriteData.java:6)
chmod +w test.txt 
java WriteData
cat test.txt 
ABB6BB6
FileReader code Example, markSupported(), getEncoding(), read(), read(char[])
cat ReadData.java 
import java.io.*;
public class ReadData {
    public static void main(String[] args) {
        try(FileReader fr = new FileReader("test.txt");) {
            System.out.println(fr.markSupported());
            System.out.println(fr.getEncoding());
            System.out.print((char)fr.read());
            char[] cbuf = new char[2];
            fr.read(cbuf);
            System.out.println(new String(cbuf)); 
            int data = 0;
            while( (data = fr.read()) != -1) {
                System.out.print((char)data);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
cat test.txt 
abcABC,123456
javac ReadData.java 
java ReadData
false
UTF8
abc
ABC,123456
chmod -r test.txt 
javac ReadData.java 
java ReadData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(FileInputStream.java:138)
 at java.io.FileInputStream.(FileInputStream.java:93)
 at java.io.FileReader.(FileReader.java:58)
 at ReadData.main(ReadData.java:4)
chmod +r test.txt 
java ReadData
false
UTF8
abc
ABC,123456
BufferedReader code example: readLine(), markSupported(), mark(int), reset(), skip(), read(char), read(char[]).
cat ReadData.java
import java.io.*;
public class ReadData {
    public static void main(String[] args) {
        try(BufferedReader fr = new BufferedReader(new FileReader("test.txt"))) {
            System.out.println(fr.readLine());
            System.out.println(fr.markSupported());
            fr.mark(10);
            System.out.print((char)fr.read());
            char[] cbuf = new char[2];
            fr.read(cbuf);
            System.out.println(new String(cbuf)); 
            fr.reset();
            System.out.println(fr.readLine());
            fr.skip(5);
            int data = 0;
            while( (data = fr.read()) != -1) {
                System.out.print((char)data);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
cat test.txt 
ABB6
abcdefghijk
123456789

javac ReadData.java 
java ReadData
ABB6
true
abc
abcdefghijk
6789
chmod -r test.txt 
java ReadData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(FileInputStream.java:138)
 at java.io.FileInputStream.(FileInputStream.java:93)
 at java.io.FileReader.(FileReader.java:58)
 at ReadData.main(ReadData.java:4)
chmod +r test.txt 
java ReadData
ABB6
true
abc
abcdefghijk
6789

FileWriter code example. write(int), write(char), write(char cbuf[], int off, int len), write(String), write(String, int off, int len), append(int), append(char), append(String), append(CharSequence csq, int start, int end), flush(), getEncoding().
cat WriteData.java 
import java.io.*;
public class WriteData
{
  public static void main(String args[]) throws FileNotFoundException
  {
    try(FileWriter fr = new FileWriter("test.txt")) {
        fr.write('A');
        char[] buf = new char[]{'B', 66, '6'};
        fr.write(buf, 0, buf.length);
        fr.write("hell");
        fr.write("hello", 4, 1);
        fr.append(',');
        fr.append(" OCPJP");
        fr.append(" xxxxx!", 6, 7);
        //delegate to StreamEncoder, need to flush
        fr.flush();
        System.out.println(fr.getEncoding());
        //try with resources, no need to close
        //fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
  }
}
javac WriteData.java 
java WriteData
UTF8
cat test.txt 
ABB6hello, OCPJP!
java WriteData
UTF8
cat test.txt 
ABB6hello, OCPJP!
vi WriteData.java 
grep test.txt WriteData.java 
    try(FileWriter fr = new FileWriter("test.txt", true)) {
echo 'append set to true'
append set to true
javac WriteData.java 
java WriteData
UTF8
cat test.txt 
ABB6hello, OCPJP!ABB6hello, OCPJP!
chmod -w test.txt 
java WriteData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:213)
 at java.io.FileOutputStream.(FileOutputStream.java:133)
 at java.io.FileWriter.(FileWriter.java:78)
 at WriteData.main(WriteData.java:6)
chmod +x test.txt 
java WriteData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:213)
 at java.io.FileOutputStream.(FileOutputStream.java:133)
 at java.io.FileWriter.(FileWriter.java:78)
 at WriteData.main(WriteData.java:6)
chmod -x test.txt 
chmod +w test.txt 
java WriteData
UTF8
cat test.txt 
ABB6hello, OCPJP!ABB6hello, OCPJP!ABB6hello, OCPJP!
BufferedWriter code example, write(char), write(char[], int, int), newLine(), append(char), append(String, int, int), flush().
cat WriteData.java 
import java.io.*;
public class WriteData
{
  public static void main(String args[]) throws FileNotFoundException
  {
    try(BufferedWriter fr = new BufferedWriter(new FileWriter("test.txt"))) {
        fr.write('A');
        char[] buf = new char[]{'B', 66, '6'};
        fr.write(buf, 0, buf.length);
        fr.newLine();  //line break
        fr.write("hell");
        fr.write("hello", 4, 1);
        fr.append(',');
        fr.append(" OCPJP");
        fr.append(" xxxxx!", 6, 7);
        fr.flush();
        //try with resources, no need to close
        //fr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
  }
}
javac WriteData.java 
java WriteData
cat test.txt 
ABB6
hello, OCPJP!
chmod -w test.txt 
java WriteData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:213)
 at java.io.FileOutputStream.(FileOutputStream.java:101)
 at java.io.FileWriter.(FileWriter.java:63)
 at WriteData.main(WriteData.java:6)
chmod +w test.txt 
java WriteData
cat test.txt 
ABB6
hello, OCPJP!
ObjectOutputStream code example, writeObject(Object)
cat WriteData.java 
import java.io.*;
import java.util.*;
public class WriteData
{
  public static void main(String args[]) throws FileNotFoundException
  {
    try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.txt"))) {
        out.write('A');
        byte[] buf = new byte[]{'B', 66, '6'};
        out.write(buf, 0, buf.length);
        out.write(buf);
        out.writeObject(new Date());
        out.writeObject(new Date());
        out.flush();  //need to flush
        //try with resources, no need to close
        //out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
  }
}

javac WriteData.java 
java WriteData
cat test.txt 
??wABB6BB6srjava.util.Datehj?KYtxpY篷Gxsq~Y篷Lx
chmod -w test.txt 
java WriteData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:213)
 at java.io.FileOutputStream.(FileOutputStream.java:101)
 at WriteData.main(WriteData.java:7)
chmod +w test.txt 
java WriteData
cat test.txt 
??wABB6BB6srjava.util.Datehj?KYtxpY?hgxsq~Y?hnx

ObjectInputStream code example: readObject().
cat ReadData.java 
import java.io.*;
import java.nio.charset.*;
import java.util.*;
public class ReadData {
    public static void main(String[] args) {
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.txt"))) {
            System.out.println(in.markSupported());
            System.out.println((char)in.read());
            byte[] buf = new byte[2];
            in.read(buf);
            System.out.println(new String(buf)); 
            int lengthRead = 0;
            while((lengthRead = in.read(buf)) > 0) {
                System.out.print(new String(buf, 0, lengthRead, StandardCharsets.UTF_8));
            }
            System.out.println();
            Date d = (Date)in.readObject();
            System.out.println(d.getTime());
            d = (Date)in.readObject();
            System.out.println(d.getTime());
            d = (Date)in.readObject();
        } catch (IOException | ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

cat test.txt 
??wABB6BB6srjava.util.Datehj?KYtxpY?hgxsq~Y?hnx

javac ReadData.java 
java ReadData
false
A
BB
6BB6
1485650815079
1485650815086
java.io.EOFException
 at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2601)
 at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
 at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
 at ReadData.main(ReadData.java:21)

chmod -r test.txt 
java ReadData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(FileInputStream.java:138)
 at java.io.FileInputStream.(FileInputStream.java:93)
 at ReadData.main(ReadData.java:6)
chmod +r test.txt 
java ReadData
false
A
BB
6BB6
1485650815079
1485650815086
java.io.EOFException
 at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2601)
 at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
 at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
 at ReadData.main(ReadData.java:21)
PrintWriter code example: write(char), write(char[]), write(String), print(String), format(String), printf(String), println(), println(String).
cat WriteData.java 
import java.io.*;
import java.util.*;
public class WriteData
{
  public static void main(String args[]) throws FileNotFoundException
  {
    try(PrintWriter out = new PrintWriter(new FileOutputStream("test.txt"))) {
        out.write('A');
        char[] buf = new char[]{'B', 66, '6'};
        out.write(buf, 0, buf.length);
        out.write(buf);
        out.println();
        out.print("in OCPJP, print(String), ");
        out.write("write(String), ");
        out.format("format(String), ");
        out.printf("printf(String) are the same");
        out.println("!");
        out.flush();  //need to flush
        //try with resources, no need to close
        //out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
  }
}

javac WriteData.java 
java WriteData
cat test.txt 
ABB6BB6
in OCPJP, print(String), write(String), format(String), printf(String) are the same!
chmod -w test.txt 
java WriteData
java.io.FileNotFoundException: test.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:213)
 at java.io.FileOutputStream.(FileOutputStream.java:101)
 at WriteData.main(WriteData.java:7)
chmod +w test.txt 
java WriteData
cat test.txt 
ABB6BB6
in OCPJP, print(String), write(String), format(String), printf(String) are the same!