Java File I/O - City University of New York

Java File I/O All file related I/O classes are in the java.io package. A stream is an object that permits the flow of data between a program and an I/O device. An input stream permits the flow from the device to the program, and an output stream permits the flow from the program to the device. Streams are used for console I/O and file I/O.





A file is a collection of items stored on an external device. Files provide both sequential and random access. The 2 types of files in Java are text files and binary files. A text file can be considered to be a sequence of characters (and can be conveniently read in a text editor,) and a binary file can be considered as a sequence of bytes. The Java object FileStream provides access to data values. The classes, InputStream and OutputStream, are used to read and write bytes and process binary files. The Reader and Writer classes are used to read and write 16-bit Unicode character values and process text files. The File class provides methods for dealing with files and directories. File systems are organized into a hierarchy with a root folder/directory and subfolders/subdirectories. A path is a description of a file's location in the hierarchy.

1





2

Creating a Handle to a File

A handle to a file is created by passing the path to the file as an argument to the constructor for the File object:

File inputFile = new File ("text.txt");

Reading from a Text File

A text file can be read using a Scanner object. Using the Scanner offers the advantage of using the methods that come with the Scanner class.

The following source code uses the Scanner class to read from a text file:

import java.util.Scanner; import java.io.*;

public class Reading { public static void main (String [] args) { String line = null; Scanner scan = null;

try { scan = new Scanner(new File("lorem.txt")); // read and output each line while (scan.hasNextLine()) { line = scan.nextLine(); System.out.println(line); }

} catch (IOException e) { System.out.println("Error accessing file"); e.printStackTrace();

} finally { scan.close();

} } }

Replace the line below:

in = new Scanner(new File("lorem.txt"));

To read from an URL address instead of reading from a local file:

URL url = new URL(""); scan = new Scanner(url.openStream());

You may have to add a catch block to handle a possible MalformedURLException.

3

The following source code uses the BufferedReader class to read from a text file:

import java.io.*; public class Reading {

public static void main (String [] args) { String line = null; BufferedReader in = null; try { // open the file using an URL in = new BufferedReader(new FileReader("lorem.txt")); // read and output each line while ((line = in.readLine()) != null) System.out.println(line); } catch (IOException e) { System.out.println("Error accessing file"); } finally { try { in.close(); } catch (IOException e) { System.out.println("Problem closing the stream"); }

} }

Replace the line below:

in = new BufferedReader(new FileReader("lorem.txt"));

To read from an URL address instead of reading from a local file:

URL url = new URL(""); in = new BufferedReader(new InputStreamReader(url.openStream()));

You may have to add a catch block to handle a possible MalformedURLException.

Note: The hasNextLine method in Scanner class returns a Boolean value to indicate the end of the file, but the readLine method in the BufferedReader class returns null to indicate the end of file.

4

Writing to a Text File

The PrintWriter class can be used to write text data to a file. If the file does not exist a new file will be created, but if the file exists the data in the file will be deleted. This class has methods print(), printf() and println() that permit writing to a file.

You can use a PrinterWriter to wrap a FileOutputStream.

PrintWriter pw = new PrintWriter(new FileOutputStream ("outputFile.txt"));

You can use a PrintWriter to wrap a File.

PrintWriter pw = new PrintWriter(new File("outputFile.txt"));

The following source code reads from a text file using the Scanner class and writes the output to another text file using the PrintWriter class:

import java.util.Scanner; import java.io.*;

public class TextFile { public static void main (String [] args) {

String line = null; Scanner in = null; PrintWriter out = null;

try {

// create handles to the files and connect them to the streams in = new Scanner(new File("Sudoku.txt")); out = new PrintWriter(new File("testfile.txt"));

// read and output each line while (in.hasNextLine()) {

line = in.nextLine();

// read a line from a text file

System.out.println(line);

out.println(line);

// write a line to a text file

}

} catch (FileNotFoundException fnfe) { System.out.println("File not found..."); fnfe.printStackTrace();

} finally { in.close(); out.close();

} } }

5

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download