Java Streams   «Prev 

FileOutputStream write() example

The following code fragment writes the string "This program writes a string to a file named test.datat" into the file "test.data".
package com.java.bytestreams;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDriver {
 public static void main(String[] args) {
  try {
   FileOutputStream fos = new FileOutputStream("test.data");
   String s = "This program writes a string to a file named test.data";
   byte[] b = s.getBytes();
   for (int i = 0; i < b.length; i++) {
    fos.write(b[i]);
   }
   fos.close();
  } // end -try
  catch (IOException e) {
   System.err.println(e);
  }
 }
}

The following String will be written to the file test.data".
This program writes a string to a file named test.data

InputStream, OutputStream

A stream can be defined as a sequence of data, there are two kinds of Streams.
  1. InputStream: The InputStream is used to read data from a source.
  2. OutputStream: The OutputStream is used for writing data to a destination.

Streams consisting of Source, Program and Destination
Streams consisting of Source, Program and Destination

Java provides flexible support for I/O related to files and networks. This page discusses very basic functionality related to streams and I/O.

Byte Streams

Java Byte Streams are used to perform input and output of 8-bit bytes. Although there are many classes related to byte streams, the most frequently used classes are:
  1. FileInputStream and
  2. FileOutputStream.

Executing the Java Class

The following example makes use of two classes to copy an input file to an output file.
1. Running CopyFile.java from Eclipse
When running the following file in Eclipse, make sure the file "input.txt" is at the same level as your 1) bin and 2) src folders. Let us use a file input.txt with the following content.
This is test for copy file.
package com.java.bytestreams;
import java.io.*;

public class CopyFile {
 public static void main(String args[]) throws IOException   {
   FileInputStream in = null;
   FileOutputStream out = null;
   try {
      in = new FileInputStream("input.txt");
      out = new FileOutputStream("output.txt");
      
      int c;
      while ((c = in.read()) != -1) {
         out.write(c);
      }
   }finally {
      if (in != null) {
         in.close();
      }
      if (out != null) {
         out.close();
      }
   }
 }
}

1. Running CopyFile.java from the Command Prompt
a) Compile the above program.
Put the above code in CopyFile.java file and execute the following from the command line on Unix or Linux machine.
$javac CopyFile.java

b) Execute CopyFile.java, which will result in creating the output.txt file with the same content as the "input.txt" file.
$java CopyFile

Ad Java7 NIO 2