How do I write the contents of a file to standard output?
Author: Deron Eriksson
Description: This Java tutorial describes how to write the contents of a file to standard output.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
An InputStream reads a stream of bytes into a JavaSW application. A FileInputStream is an InputStream that allows us to read bytes from a file. To read the contents of a file into a Java application, we can create a FileInputStream to the file and call its read() method to read its bytes one at a time. An OutputStream outputs a stream of bytes from a Java application. System.out is a PrintStream, which is a type of OutputStream. System.out by default writes its output to the console (ie, standard output). We can write to System.out one byte at a time using its write() method. The WriteFileContentsToStandardOutput class reads from a text file one byte at a time and outputs the result to System.out one byte at a time. The FileInputStream returns -1 when it reaches the end of the file. Notice that System.out.flush() is called, which can be necessary to flush out the standard output PrintStream. WriteFileContentsToStandardOutput.javapackage test; import java.io.File; import java.io.FileInputStream; public class WriteFileContentsToStandardOutput { public static void main(String[] args) throws Exception { File file = new File("testfile.txt"); FileInputStream fis = new FileInputStream(file); int oneByte; while ((oneByte = fis.read()) != -1) { System.out.write(oneByte); // System.out.print((char)oneByte); // could also do this } System.out.flush(); } } Related Tutorials:
|