You are on page 1of 12

Java I/O

Solutions to
Workshops
Java I/O: Solutions to Workshops Page i

Contents

Lesson 2: Using Text Streams ........................................................................................................1


Lesson 4: Using Serialization ...........................................................................................................4
Lesson 6: Using Piped Streams .......................................................................................................6
Lesson 7: Displaying File Information ..............................................................................................9

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 1

Lesson 2:
Using Text Streams

// TextFileReaderWriter.java
package mycode;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import java.util.Vector;
import java.util.Iterator;

public class TextFileReaderWriter {

public static void main(String[] args) {


String inputFileName;
String outputFileName;
String serializedObjectName;
Vector vec;

TextFileReaderWriter tfrw = new TextFileReaderWriter();

if (args.length < 1) {
tfrw.info(
"{Input File Name} [{output File Name}] [{name of serialized
vector}]");
return;
}
inputFileName = args[0];

tfrw.info("Reading file: " + inputFileName);

vec = tfrw.readTextFile(inputFileName);

if (vec == null) {
return;
}

tfrw.info("Read " + vec.size() + " lines from input file");

if (args.length < 2 || args[1].length() == 0) {

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 2

tfrw.printLines(vec);
} else {
outputFileName = args[1];
tfrw.info("Writing file " + outputFileName);
tfrw.writeTextFile(outputFileName, vec);
}

if (args.length == 3 && args[2].length() != 0) {


serializedObjectName = args[2];
tfrw.info("Serializing vector to file " + serializedObjectName);
tfrw.serializeVector(serializedObjectName, vec);
}
}

//------------------------------------------------
// Read input from text file
//------------------------------------------------
public Vector readTextFile(String inputFileName) {
try {
Vector vec = new Vector();
FileReader fr = new FileReader(inputFileName);
BufferedReader br = new BufferedReader(fr);

String strLine = br.readLine();

while (strLine != null) {


vec.add(strLine);
strLine = br.readLine();
}
br.close();
return vec;
} catch (Exception e) {
info("Exception in readTextFile():");
info(e.getClass().getName());
info(e.getMessage());
return null;
}
}

//------------------------------------------------
// Print to standard output
//------------------------------------------------
public void printLines(Vector vec) {
Iterator iter = vec.iterator();

while (iter.hasNext()) {
System.out.println((String) iter.next());
}
}

//------------------------------------------------
// Write to a text file
//------------------------------------------------
public void writeTextFile(String outputFileName, Vector vec) {
try {
FileWriter fw = new FileWriter(outputFileName);
PrintWriter pw = new PrintWriter(fw);
Iterator iter = vec.iterator();

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 3

while (iter.hasNext()) {
pw.println((String) iter.next());
}
pw.close();
} catch (Exception e) {
info("Exception in writeTextFile():");
info(e.getClass().getName());
info(e.getMessage());
}
}
//------------------------------------------------
// Serialize the vector
//------------------------------------------------
public void serializeVector(String fileName, Vector vec) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(vec);
oos.close();
} catch (Exception e) {
info("Exception in writeObjectFile():");
info(e.getClass().getName());
info(e.getMessage());
}
}

public void info(Object o) {


System.err.println(getClass().getName() + " " + o.toString());
}
}

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 4

Lesson 4:
Using Serialization

// SerializedObjectReader.java
package mycode;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

import java.util.Vector;
import java.util.Iterator;

public class SerializedObjectReader {

public static void main(String[] args) {


String serializedObjectName;
Vector vec;

SerializedObjectReader sor = new SerializedObjectReader();

if (args.length < 1) {
sor.info(
"{name of serialized vector} [-print]");
return;
}
serializedObjectName = args[0];

sor.info("Deserializing " + serializedObjectName);

vec = sor.readObjectFile(serializedObjectName);

if (vec == null) {
return;
}

if (args.length == 2 && args[1].equals("-print")) {


sor.info("Lines in deserialized vector: " + vec.size());
}

sor.printLines(vec);
}

//------------------------------------------------
// Print to standard output
//------------------------------------------------

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 5

public void printLines(Vector vec) {


Iterator iter = vec.iterator();

while (iter.hasNext()) {
System.out.println((String) iter.next());
}
}

// ------------------------------------------------
// Read serialized object (in this case a Vector)
// and reconstitute it in a Vector object
//------------------------------------------------
public Vector readObjectFile(String strFileName) {
try {
Vector vec;

FileInputStream fis = new FileInputStream(strFileName);


ObjectInputStream oos = new ObjectInputStream(fis);
vec = (Vector) oos.readObject();
oos.close();
return vec;
} catch (Exception e) {
info("Exception in readObjectFile():");
info(e.getClass().getName());
info(e.getMessage());
return null;
}
}

public void info(Object o) {


System.err.println(getClass().getName() + " " + o.toString());
}
}

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 6

Lesson 6:
Using Piped Streams

/*
EchoApp.java

Echo Application: after pipe stream lab.


*/
package mycode;
import course.echo.EchoGUI;
import course.application.*;
import java.io.*;

public class EchoApp extends ApplicationBase {

//================================================
// Instance Variables
//================================================
private EchoGUI _gui;
private String _strInput;

//================================================
// GUI methods
//================================================

//------------------------------------------------
// Send input to pipe
//------------------------------------------------
public void sendMessage(String strMsg) {
// Start a thread to send output
synchronized(this) {
_strInput = strMsg;
notifyAll();
}
}

// Called after GUI is created.


public void init() {
_gui = (EchoGUI) getGui();

PipedReader pipeR;
PipedWriter pipeW;

// Create PipedReader
pipeR = new PipedReader();

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 7

//------------------------------------------------
// Lab: create PipedWriter connected to PipedReader
//------------------------------------------------
try {
pipeW = new PipedWriter(pipeR);
}
catch(IOException e) {
System.out.println("Can't create PipedWriter:\n" + e);
return;
}

// Start a thread to read and display output


(new InputThread(pipeW)).start();

// Start a thread to read and display output


(new OutputThread(pipeR)).start();
}

public void quit() {


System.exit(0);
}

//================================================
// Private Inner Class: InputThread
//================================================
private class InputThread extends Thread {
private PrintWriter _pwPipe;

public InputThread(PipedWriter pipeW) {


//------------------------------------------------
// Lab: initialize PrintWriter _pwPipe from PipedWriter
//------------------------------------------------
_pwPipe = new PrintWriter(pipeW);
}

public void run() {


System.out.println("Input thread started");
try {
while(true) {
synchronized(EchoApp.this) {
while(_strInput == null) {
try {
EchoApp.this.wait();
}
catch(InterruptedException e) {
}
}

feedString(_strInput);

_strInput = null;
EchoApp.this.notify();
}
}
}
catch(IOException e) {

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 8

System.out.println("Input thread " + e);


return;
}
}

private void feedString(String strInput)


throws IOException {

//------------------------------------------------
// Lab: create StringReader from _strInput
//------------------------------------------------
StringReader sr = new StringReader(_strInput);
BufferedReader br = new BufferedReader(sr);

//------------------------------------------------
// Lab: read string line by line
//------------------------------------------------
String str = br.readLine();
while(str != null) {
_pwPipe.println(str);
str = br.readLine();
}
}
}
//================================================
// Private Inner Class: OutputThread
//================================================
private class OutputThread extends Thread {
BufferedReader _br;

public OutputThread(PipedReader pipeR) {


//------------------------------------------------
// Lab: initialize BufferedReader _br from PipedReader
//------------------------------------------------
_br = new BufferedReader(pipeR);
}

public void run() {


String str;
while(true) {
//------------------------------------------------
// Lab: read line from _br into str
//------------------------------------------------
try {
str = _br.readLine();
}
catch(IOException e) {
System.out.println("Output thread " + e);
return;
}
_gui.displayLine(str);
}
}
}
} // End of EchoApp class

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 9

Lesson 7:
Displaying File Information

//FileDescriptorApp.java
import java.io.*;

public class FileDescriptorApp {


private static PrintStream _ps = System.out;

public static void main(String[] args) throws IOException {


File file = new File(args[0]);

System.out.println("Information about " + args[0] + ":");

if(file.exists()) {
// Display general stuff:
System.out.println("Absolute path: "
+ file.getAbsolutePath());
System.out.println("Canonical path: "
+ file.getCanonicalPath());

// For directories:
if(file.isDirectory()) {
System.out.println(args[0]
+ " is a directory. It contains:");

// Display list of files


System.out.println();

String[] files;
if( args.length > 1 )
files = file.list(new FileFilter(args[1]));
else
files = file.list();
for( int i = 0; i < files.length; i++ ) {
System.out.println((i+ 1) + ". " + files[i]);
}
}

// Normal files:
else if(file.isFile()) {
System.out.println(args[0] + " is a file.");
}
}

© 2003 SkillBuilders, Inc. V 1.2


Java I/O: Solutions to Workshops Page 10

else
System.out.println("File does not exist.");
}

private static class FileFilter implements FilenameFilter {


private String _strExt;
public FileFilter(String strExt) {
_strExt = strExt.toUpperCase();
}

public boolean accept(File dir, String name) {


return name.toUpperCase().endsWith(_strExt);
}
}
}

© 2003 SkillBuilders, Inc. V 1.2

You might also like