java.io package.
java.io.InputStream and
java.io.OutputStream. Classes that inherit these
can be used for writing and reading of bytes.InputStream » FileInputStreamOutputStream » FileOutputStreamCopyBytes.java (source:
Java Tutorial » Byte Streams)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
java.io.Reader and
java.io.Writer. Classes that inherit these
can be used for writing and reading of bytes.Reader » InputStreamReader » FileReaderWriter » OutputStreamWriter » FileWriterInputStreamReader and OutputStreamReader
are byte-to-character "bridge" streams.CopyCharacters.java (source:
Java Tutorial » Character Streams)
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
BufferedReader and BufferedWriter
classes
FileReader reader = new FileReader("file.txt");
BufferedReader bufferedreader = new BufferedReader(reader);
CopyLines.java (source:
Java Tutorial » Character Streams)
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class CopyLines {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream =
new BufferedReader(new FileReader("xanadu.txt"));
outputStream =
new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
SerializableObjectInputStream
and ObjectOutputStream and their writeObject and readObject methodsOpenAndSaveCar.java
import java.io.*;
class Car implements Serializable {
private String brand;
public Car(String brand) {
setBrand(brand);
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
class OpenAndSaveCar {
public static void main(String [] args) {
Car datsun = new Car("Datsun 100a");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
// Save the object
fos = new FileOutputStream("car.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(datsun);
// Read the object
fis = new FileInputStream("car.dat");
ois = new ObjectInputStream(fis);
Car datsun2 = (Car) ois.readObject();
System.out.println(datsun2.getBrand());
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(fos != null) {
fos.close();
}
if(oos != null) {
oos.close();
}
if(fis != null) {
oos.close();
}
if(ois != null) {
oos.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
transient
keywordjava.io is suitable for basic needs. When
there is a need for higher performance, use
Java NIO (New I/O) (java.nio)java.iojava.io » Stream: movement of single bytes one at a time.java.nio » Block: movement of many
bytes (blocks) at a timejava.iojava.nio must go through
a ChannelBuffer is a container object, before sending data
into a channel, the data must be wrapped inside a Bufferjava.nio.Buffer:
ByteBuffer - byte arrayCharBufferShortBufferIntBufferLongBufferFloatBufferDoubleBufferFileInputStream fin = new FileInputStream( "data.txt" ); // Get a channel via the FileInputStream FileChannel fc = fin.getChannel(); // Create a buffer ByteBuffer buffer = ByteBuffer.allocate( 1024 ); // Read from channel into a buffer fc.read( buffer );
FileOutputStream fout = new FileOutputStream( "data.txt" );
// Get a channel via the FileOutputStream
FileChannel fc = fout.getChannel();
// Create a buffer
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
// Data to be saved
byte [] message = "this will be saved".toByteArray();
// Write into buffer
for ( int i=0; i<message.length; i++ ) {
buffer.put( message[i] );
}
// Flip the buffer, this will be explained later
buffer.flip();
// Writes SOME bytes from the buffer!
fc.write( buffer );
position, limit
and capacityposition: is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit.limit: is the index of the first element that should not be read or written. A buffer's limit is never negative and is never greater than its capacitycapacity: is the number of elements buffer contains. The capacity of a buffer is never negative and never changes.





The position cannot go past the limit!

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class CopyFiles {
public static void main(String args []) throws Exception {
// Must be started given input and output files
if (args.length<2) {
System.err.println("Usage: java CopyFile infile outfile");
System.exit(1);
}
String infile = args[0];
String outfile = args[1];
// Get streams to the files
FileInputStream fin = new FileInputStream (infile);
FileOutputStream fout = new FileOutputStream(outfile);
// Get channels to the files
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
// Create byte buffer to be used in reading and writing
ByteBuffer buffer = ByteBuffer.allocate(1024);
// Let's start reading and writing
while (true) {
// Set the position = 0
// Set limit to capacity (1024)
buffer.clear();
// Read sequence of bytes from the infile into a buffer
int numberOfReadBytes = fcin.read(buffer);
// If there is no bytes left in the infile, break
// out of the loop
if (numberOfReadBytes == -1) {
break;
}
// Limit is set to position
// and then the position is set to zero
buffer.flip();
// write all the bytes from the buffer to outfile
int numberOfWrittenBytes = 0;
do {
numberOfWrittenBytes += fcout.write(buffer);
}
while(numberOfWrittenBytes < numberOfReadBytes);
}
}
}