Java IO – Pipes And Print Writer Next

Read from Console using pipes

We see the use of a buffered reader and writer and a piped reader and writer. The example also demonstrates how to read from a console continuously. The example reads from a console using a buffered reader, passes the characters to a piped writer. A piped reader reads the characters and writes to a file using buffered writer

PipedReader pipedReader = new PipedReader();
PipedWriter pipedWriter = new PipedWriter(pipedReader);

screenReader reader = new screenReader(pipedWriter);
OutputWriter writer = new OutputWriter(pipedReader);
reader.start();
writer.start();

// A Reader thread to read continously from the input. The characters read are written to a piped writer
class screenReader extends Thread {
		PipedWriter writer;

		public screenReader(PipedWriter writer) {
			this.writer = writer;
		}

		@Override
		public void run() {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					System.in));
			while (true) {
				try {
					String s = reader.readLine();
					if ("exit".equals(s.trim())) {
						reader.close();
						writer.close();
						break;
					}
					writer.write(s);

				} catch (IOException e) {

				}
			}
	   }
}
// A writer thread to write data to a file. The data is read from a piped reader
class OutputWriter extends Thread {
		PipedReader reader = null;

		public OutputWriter(PipedReader reader) {
			this.reader = reader;
		}

		@Override
		public void run() {
			try {
				PrintWriter writer = new PrintWriter(new FileWriter(
						"pipedOut.txt"), true);
				BufferedReader consoleReader = new BufferedReader(reader);
				while (true) {
					String s = consoleReader.readLine();
					if (s == null) {
						reader.close();
						writer.close();
						return;
					}
					writer.println(s);

				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   }
}

Writing to a text file- PrintWriter

Print Writer is a very useful class to write to text files. It enables writing without throwing IOException and automatic flushing. It has methods to combine the step of writing a line of text, writing a new line and flushing in a single step.

//Create a PrintWriter
PrintWriter writer = new PrintWriter(new File("output.txt"));

// It is also possible to create a filewriter with automatic flushing.
// However autoflushing only happens when one of the println,printf or format methods are called.
PrintWriter writer2 = new PrintWriter(new BufferedWriter(new FileWriter(new File("output2.txt"))), true);

//Write characters to file using printwriter. All methods do the same thing
writer.append('a');
writer.write('b');
writer.print('k');

//write part of string to a file
writer.append("def", 1, 1);
writer.write("keep", 2, 2);

//write java objects to a file
writer.print(true);
// double
writer.print(1.434);
// float
writer.print(1.23f);
writer.print(2);
// writes any object to a file by calling its toString method.
writer.print(writer);

// terminates the current line. Uses the system specific line separator.
writer.println();

// use println methods with any object to write the string 
//representation of the object followed by a new line.
writer.println(3);

// Write writer formatted string to file.
// The java formatter can be used to format a string. This method writes
// formatted string to a file based on the default formatter
writer.printf("%a", 34.0);

// the flush method needs to be called explicitly unless one of the
// methods that flush automatically are called.
writer.flush();

//Check for errors since PrintWriter does not throw IOException
writer.checkError();
writer.close();

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.