File I/O
Learning Objective
Welcome to the Day4 in Java. Here we would concentrate on solving File I/O Problems.Introduction
The Java I/O means Java Input/Output. It is provided by the java.io package. This package has an InputStream and OutputStream. Java InputStream is defined for reading the stream, byte stream and array of byte stream.Java offers extensive - yet easy to use - file handling classes that make it a breeze to read and write files. In this tutorial, we'll start by covering the basics of file input and output, as well as covering some associated topics, such as trapping exceptions and I/O errors.
File output
Our first example will be a program that writes a string to a file. In order to use the Java file classes, we must import the Java input/output package (java.io) in the following manner
import java.io.*;Inside the main method of our program, we must declare a FileOutputStream object. For those familiar with C, a FileOutputStream is analogous to a file handle. When we send a stream (or sequence) of data to the FileOutputStream handle, data will be written to disk.
In Java, there exists a large number of extensions to the standard input and output stream classes. This is handy, as the basic input and output streams deal only with the transfer of bytes - not the easiest way for us to write out data. There's a wide variety of streams to choose from : if we were writing data such as bytes, integers, floats, or other "data" orientated types, we might choose the DataOutputStream, whereas for text we'd use the PrintStream class.
In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then close the connection.
/* * * FileOutputDemo * * Demonstration of FileOutputStream and * PrintStream classes * */ import java.io.*; class FileOutputDemo { public static void main(String args[]) { FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try { // Create a new file output stream // connected to "myfile.txt" out = new FileOutputStream("myfile.txt"); // Connect print stream to the output stream p = new PrintStream( out ); p.println ("This is written to a file"); p.close(); } catch (Exception e) { System.err.println ("Error writing to file"); } } }
Exceptions are events that occur in exceptional or unusual circumstances, such as error conditions. A method can throw an exception, to indicate to the calling object that a non-standard circumstance has occurred. Thus, instead of checking each and every file method call, we have one piece of code handling all possible errors!
File input
File input under Java differs little from file output. We must import the Java IO package, and we create a file input stream inside of a try { .. } catch block as in the previous example.
In this example, the file we open is given to us as the first command line parameter. We obtain this by examining the args array of strings. Since an array is an actual object in Java, we can find the length of the array (and hence the number of parameters) through the length attribute.
To do anything useful with file input, we create a DataInputStream which can handle reading in data as well as lines of text. To determine if there is any data left to read, we call the available() method of our input stream. This method returns the number of bytes remaining, which we check to see is not equal to zero. Then we call the DataInputStream's readLine() method and print the result to the screen.
/* * * FileInputDemo * Demonstrates FileInputStream and * DataInputStream */ import java.io.*; class FileInputDemo { public static void main(String args[]) { // args.length is equivalent to argc in C if (args.length == 1) { try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(args[0]); // Convert our input stream to a // DataInputStream DataInputStream in = new DataInputStream(fstream); // Continue to read lines while // there are still some left to read while (in.available() !=0) { // Print file line to screen System.out.println (in.readLine()); } in.close(); } catch (Exception e) { System.err.println("File input error"); } } else System.out.println("Invalid parameters"); } }
Comments
Post a Comment