ZOFTINO.COM android and web dev tutorials

Java Input Output Character Streams

Java I/O stream API allows you to read and write different types of data from and to different types of sources and destinations. Java input output byte streams allow you to read and write 8 bit bytes data. To handle character data, you can use Java I/O character streams.

Table of Contents

Character Streams

Character streams allow you to read character data from any source and write character data to any destination. Character input and output streams automatically translate data using local character set. Reader and Writer are the super classes of all classes that are used to deal with character stream input and output.

Some of the subclasses of Reader are StringReader, InputStreamReader, CharArrayReader, BufferedReader, etc. Some of the subclasses of Writer are StringWriter, PrintWriter, OutputStreamWriter, CharArrayWriter, BufferedWriter, etc.

Methods of character input stream Reader class are close(), read(), mark(), reset(), ready() and skip(). Method close() is used to close Reader object and release resources. Method read() is used to read characters. Method mark() is used to set present position. Method reset() sets the present position to the position which is previously set by calling mark(). Method skip() allows you to skip the specified number of characters. Method ready() can be used to check whether the stream is ready for reading or not.

Reader class provides overloaded read() methods which allow you to read single character at a time, read characters into char array or read characters into character buffer.

Methods of character output stream Writer class are append(), close(), write() and flush(). Method append() allows you to add single character or character sequence to the writer. Method close() releases resource associated with the writer. Method flush() makes it write buffered data to destination. Writer provides overloaded write() methods which allow you to write single character, character array and string to writer.

The difference between append() and write() methods of Writer class is that append takes CharSequence as input that means any object which implements CharSequence interface can be passed to append() method. For example, you can pass String, StringBuilder etc. Whereas, write() method just takes String as input.

StringWriter Example

StringWriter writes data to string buffer. You can use write methods to write data to it and data can be obtained from StringWriter using toString() method. For example, below method writes content to StringWriter and returns it.

public StringWriter sendLatestOffers() throws Exception {	
	
	StringWriter sw = new StringWriter();
	//write string
	String offer = "flat 30% off on appliances";
	sw.write(offer);
	sw.flush();
	
	//write char
	sw.write(',');
	
	//write char array
	String offerTwo = "flat 20% off on tabs";
	char offerChars[] = offerTwo.toCharArray();
	sw.write(offerChars);
	
	return sw;
}

Caller of the method obtains StringWriter and gets the content.

try {
	StringWriter sw = streamUtil.sendLatestOffers();
	System.out.println("latest offer: "+sw.toString());
} catch (Exception e) {
	System.out.println("error in sending data");
}

Output:

latest offer: flat 30% off on appliances,flat 20% off on tabs

StringReader Example

StringReader is an input character stream with source data coming from string object. StringReader object is created by calling its constructor and passing string data as argument to it.

	public StringReader getLatestOffers() {
		String offer = "flat 10% off on sports";
		StringReader sr = new StringReader(offer);
		return sr;
	}

The caller of the methods reads data from StringReader object by calling read() method on it.

StringReader sr = streamUtil.getLatestOffers();
try {
	int c = sr.read();
	StringBuilder sb = new StringBuilder();
	while(c != -1) {
		sb.append((char)c);
		c = sr.read();
	}
	System.out.println("latest offer: "+sb.toString());
} catch (IOException e1) {
	System.out.println("error in getting data");
}

Output:

latest offer: flat 10% off on sports

PrintWriter Example

PrintWriter character output stream can be used to output formatted content. PrintWriter allows you to write primitive values and objects, to do that, it provide various print() and println() methods. You can write formatted content to output stream using format() and printf() methods which take format and content as arguments.

You can specify the destination of the PrintWriter output stream by passing the destination such as other output stream or file as an argument to its constructor. Below program uses file as destination and writes string and string builder to it without any format.

try {
	PrintWriter pw = new PrintWriter(file);
	
	String product = "Samsung galaxy mobile";
	//write string
	pw.append(product);
	pw.append(',');
	
	StringBuilder sb = new StringBuilder();
	sb.append("Lenovo laptop");
	sb.append(',');
	sb.append("HP tablet");	
	//write string builder
	pw.append(sb);
	
	pw.close();
} catch (Exception e) {

}

Output, content of the file.

Samsung galaxy mobile,Lenovo laptop,HP tablet

You can use println method to print new line.

PrintWriter pw = new PrintWriter(file);

String product = "Samsung galaxy mobile";
//print new line string
pw.println(product);


StringBuilder sb = new StringBuilder();
sb.append("Lenovo laptop");
//print new line string builder
pw.println(sb);

pw.close();

Here is the content of the file.

Samsung galaxy mobile
Lenovo laptop

Instead of file as destination for print writer object, you can use other output stream object as destination. For example, PrintWriter object is created with StringWriter as destination. Written content can be obtained from StringWriter object.

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);

String offer = "upto 2% cashback";
pw.print(offer);

pw.close();

System.out.println(sw.toString());

You can write formatted content to PrintWriter using format or printf methods as shown below.

try {
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw);
	
	String offer = "upto %d%% cashback";
	pw.printf(offer, 30);
	pw.println("");
	pw.printf("expires %tD", new Date());
	pw.close();
	
	System.out.println(sw.toString());
	
} catch (Exception e) {	
	e.printStackTrace();
}

PrintWriter formatted output.

upto 30% cashback
expires 05/15/18

OutputStreamWriter Example

OutputStreamWriter converts the characters written to it to bytes using default character set or the specified character set. OutputStreamWriter is used to convert character stream into byte stream. For efficiency, it is better to use OutputStreamWriter with BufferedWriter.

To use OutputStreamWriter, create an instance of OutputStreamWriter passing byte output stream instance like instance of ByteArrayOutputStream as an argument to its constructor.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(baos);

try {
	ow.append("output stream writer example");
	ow.flush();
	ow.close();
} catch (IOException e) {

}
byte b [] = baos.toByteArray();
System.out.println(baos.toString());

InputStreamReader Example

InputStreamReader converts bytes into characters using default character set or the specified character set. InputStreamReader is used to convert byte stream to character stream. For efficiency, it is better to use InputStreamReader with BufferedReader.

String testStr = "input strem reader example";
ByteArrayInputStream bais = new ByteArrayInputStream(testStr.getBytes());
InputStreamReader ir = new InputStreamReader(bais);

int b;
try {
	b = ir.read();
	while(b != -1) {
		System.out.println((char)b);
		b = ir.read();
	}
} catch (IOException e) {
	e.printStackTrace();
}

FileWriter Example

FileWriter can be used to write character files. FileWriter is a subclass of OutputStreamWriter. You can create FileWriter object using one of its constructors which take either file name or File object as arugment. To write content to a file, you can call write or append method on FileWriter object.

String file = "/store/offers/data/test.txt";
try {
	FileWriter fw = new FileWriter(file);
	
	fw.append("flat 40% off on everything");
	fw.write(System.lineSeparator());
	fw.append("extra 20% off on fashion");
	fw.close();
} catch (IOException e) {

}

When you create a FileWriter object, you can specify whether to override the contents of the file or append to it by passing boolean value to its constructor.

String file = "C:/Project/ZOFTINO/data/test.txt";
File fileObj = new File(file);
try {
	FileWriter fw = new FileWriter(fileObj, true);
	if(fileObj.exists()) {
		fw.write(System.lineSeparator());
	}
	fw.append("flat 10% off on electronics");
	fw.write(System.lineSeparator());
	fw.append("extra 30% off on shoe");
	fw.close();
} catch (IOException e) {

}

FileReader Example

FileReader can be used to read character file. FileReader is a subclass of InputStreamReader. You can create FileReader instance by calling one of its constructors passing file name or File object as argument to it. To read content of a file, you need to call read methods on FileReader object.

String file = "/store/offers/data/test.txt";
File fileObj = new File(file);

try(FileReader fr = new FileReader(fileObj)){
	
	StringBuilder sb = new StringBuilder();

	int c = fr.read();
	while (c != -1) {
		sb.append((char)c);
		c = fr.read();
	}
	System.out.println(sb.toString());
} catch (IOException e) {
	System.out.println(""+e);
}	

CharArrayWriter Example

CharArrayWriter character output stream writes to character array. You can write to CharArrayWriter using append() or write() methods. The written content can be obtained using toString method.

public CharArrayWriter getProducts() {		
	CharArrayWriter caw =  new CharArrayWriter();
	caw.append("Lenovo tablet");
	caw.append(',');
	caw.append("Hp Laptop");
	caw.append(',');
	caw.append("Samsung mobile");

	return caw;
}
		CharArrayWriter caw = streamUtil.getProducts();
		System.out.println("products: "+caw.toString());

CharArrayReader Example

Source of data for CharArrayReader is a character array. You can create instance of CharArrayReader by calling its constructor and passing char array as argument to it. Then data can be read from CharArrayReader using read() methods.

public boolean containOfferAmount(String offer) {
	char offerChars[] = offer.toCharArray();
	CharArrayReader car = new CharArrayReader(offerChars);
	
	try {
		int c = car.read();
		while(c != -1) {				
			c = car.read();				
			if('$' == (char)c) {
				return true;
			}
		}
	} catch (IOException e) {
		
	}
	return false;
}
String deal = "on mobile get $200 off";
boolean status = streamUtil.containOfferAmount(deal);
System.out.println("deal contains offer amount : "+status);

BufferedWriter Example

BufferedWriter character output stream writes text to another character output stream. As BufferedWriter buffers characters instead of writing them immediately to the target stream every time write() is called, writing characters to a destination such as file becomes efficient using BufferedWriter.

To use BufferedWriter, you need to instantiate it by passing another stream to its constructor.

try {
	FileWriter fw = new FileWriter(file);
	BufferedWriter bw = new BufferedWriter(fw);
	
	bw.write("flat 20% off on fashion");
	bw.newLine();
	bw.write("get upto $100 off on mobiles");
	
	bw.close();
} catch (IOException e) {

}

BufferedReader Example

BufferedReader allows you to efficiently read text from a character input stream. What makes it efficient is that it buffers text so that every call to read() or readLine() method doesn’t result in reading bytes from source stream and converting bytes into characters instead it returns it from buffer.

To use BufferedReader, you need to instantiate it by calling its constructor and passing source input stream such as FileReader as an argument to it.

In addition to read() methods, BufferedReader provide readLine() method for reading text from source. It also offers lines() method which allows you to get stream of lines from source. Below example shows how to use BufferedReader to read data from a file via FileReader.

StringBuilder sb = new StringBuilder();
try {
	FileReader fr = new FileReader(file);
	BufferedReader br = new BufferedReader(fr);			
	
	String line;
	while((line = br.readLine()) != null) {
		sb.append(line);
		sb.append("\n");
	}
br.close();
} catch (Exception e) {

}
System.out.println("file content "+sb.toString());

You can get a stream of all lines of a file using lines() method of BufferedReader.

FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);		

Stream<String> st = br.lines();

st.forEach(new Consumer<String>() {
	@Override
	public void accept(String t) {
		//do something with each line from file
		System.out.println(t.toUpperCase());
	}
	
});
br.close();

Other Tutorials Related to Java IO