We have been coming across several Files Operation in Java for several million years now , since the Flinstone kids started ridding those fancy Dinosaurs. Well , we kids (slightly grown-up kids rather) prefer blogging instead...So here I am , with an collection of quite a few handy APIs. Nothing of much use for the Experts , but might come handy for the Newbies :
The Java.io package is used for system input and output through data streams, and serialization. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects.A program uses an input stream to read data from a source.A program uses an output stream to write and send data to a destination.Java has Two types of streams- Byte & Characters.
BYTE STREAM DATA HANDLING : (All byte stream classes extends 'InputStream' and 'OutputStream')
Buffered Streams : BufferedInputStream and BufferedOutputStream :
Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. Those buffered API wrap the unbuffered streams: BufferedInputStream and BufferedOutputStream.
DataInputStream and DataOnputStream :
The DataInputStream class enables you to read Java primitives from InputStream's instead of only bytes. You wrap an InputStream in a DataInputStream and then you can read primitives from it.
CHARACTER STREAM DATA HANDLING : (All byte stream classes extends 'Reader' and 'Writer'.)
Character streams works with the characters rather than the byte. In Java characters are stored by following the Unicode (allows a unique number for every character) conventions. In such kind of storage characters becomes the platform independent, program independent, language independent. Characters storage using Unicode convention makes the Java ready for internationalization and for this Java provides the Character stream I/O. Character stream I/O is helpful for internationalization because it automatically translated the internal format to and from the local character set.
Java IO's Reader and Writer work much like the InputStream and OutputStream with the exception that Reader and Writer are character based. They are intended for reading and writing text.
Reader and Writer :
The Reader is the baseclass of all Reader's in the Java IO API. Subclasses include a BufferedReader, PushbackReader etc.Notice, that while an InputStream returns one byte at a time, meaning a value between -128 and 127, the Reader returns a char at a time, meaning a value between 0 and 65535.
The Writer class is the baseclass of all Writer's in the Java IO API.
FileReader and FileWriter :
FileReader : The FileReader class makes it possible to read the contents of a file as a stream of characters. It works much like the FileInputStream except the FileInputStream reads bytes, whereas the FileReader reads characters. The FileReader is intended to read text, in other words. One character may correspond to one or more bytes depending on the character encoding scheme.The FileReader object also lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
FileWriter : This class is used to write to character files.Creation of a FileWriter is not dependent on the file already existing. FileWriter will create the file before opening it for output when you create the object. Its write() methods allow you to write character(s) or Strings to a file. FileWriters are usually wrapped by higher-level Writer objects such as BufferedWriters or PrintWriters, which provide better performance and higher-level, more flexible methods to write data.
BufferedReader and BufferedWriter :
A BufferedReader and a BufferedWriter act like BufferedOutputStream and BufferedInputStream, except they deal with reading and writing characters.As we mentioned, a BufferedWriter allows us to write to a buffer. It applies buffering to a character output stream, improving output efficiency by combining many small write requests into a single larger request.This class has an interesting additional method that makes Java code portable. Most of the time, a new line is represented by a \n, but it may not be in all operating systems. Because of this, the Java language adds a method called newLine(). Instead of outputting the character \n, you call newLine() and that outputs the appropriate new-line character for the particular operating system that you are running on. In most cases, this will be \n.
RANDOM ACCESS FILES IN JAVA :
The RandomAccessFile class in the Java IO API allows you to move around a file and read from it or write to it as you please. You can replace existing parts of a file too. This is not possible with the FileInputStream or FileOutputStream.Few salient features are as follows :
FEW OTHER USEFUL EXAMPLES :
Few other examples that might help you guys.
Creating new Directory for writing :
Reading a Directory Recursively :
Reading from web-service and other HTTP responses :
Reading through "input" parameter from JSP (multi-part file upload):
The Java.io package is used for system input and output through data streams, and serialization. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects.A program uses an input stream to read data from a source.A program uses an output stream to write and send data to a destination.Java has Two types of streams- Byte & Characters.
BYTE STREAM DATA HANDLING : (All byte stream classes extends 'InputStream' and 'OutputStream')
For reading and writing binary data, byte stream is incorporated.Programs use byte streams to perform byte input and output.
1. Performing InputStream operations or OutputStream operations means generally having a loop that reads the input stream and writes the output stream one byte at a time.
2. You can use buffered I/O streams for an overhead reduction (overhead generated by each such request often triggers disk access, network activity, or some other operation that is relatively expensive).
InputStream and OutputStream :
The InputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of input streams.The InputStream class defines methods for reading bytes or arrays of bytes, marking locations in the stream, skipping bytes of input, finding out the number of bytes available for reading, and resetting the current position within the stream. An input source can be a file, a string, or memory that may contain the data.An input stream is automatically opened when you create it.You can explicitly close a stream with the close method.Or , let it be closed implicitly when the InputStream is garbage collected.
The InputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of input streams.The InputStream class defines methods for reading bytes or arrays of bytes, marking locations in the stream, skipping bytes of input, finding out the number of bytes available for reading, and resetting the current position within the stream. An input source can be a file, a string, or memory that may contain the data.An input stream is automatically opened when you create it.You can explicitly close a stream with the close method.Or , let it be closed implicitly when the InputStream is garbage collected.
The OutputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of output streams.OutputStream defines methods for writing bytes or arrays of bytes to the stream.An output stream is automatically opened when you create it. You can explicitly close an output stream with the close method, or let it be closed implicitly when the OutputStream is garbage collected, which occurs when the object is no longer referenced.
FileInputStream and FileOutputStream :
FileInputStream : It contains the input byte from a file and implements an input stream.
FileOutputStream : It uses for writing data to a file and also implements an output stream.
public class FileHandling { public static void main(String [ ] args) throws IOException { FileInputStream inputStream = new FileInputStream ("Input.txt") ; FileOutputStream outputStream = new FileOutputStream("Output.txt",true) ; byte[] buffer = new byte[1024]; //For larger files we specify a buffer size which defines the chunks size for data int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) outputStream.write(buffer, 0, bytesRead); wr.close() ; fr.close() ; } }
int ch; StringBuffer strContent = new StringBuffer(""); FileInputStream fin = new FileInputStream(file); while( (ch = fin.read()) != -1) strContent.append((char)ch); File logFile=new File(FilePath); FileOutputStream fop=new FileOutputStream(logFile); for(int i=0;i<100;i++){ str="hello there "+i+" times"+'\n'; fop.write(str.getBytes()); fop.flush(); }
Buffered Streams : BufferedInputStream and BufferedOutputStream :
Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. Those buffered API wrap the unbuffered streams: BufferedInputStream and BufferedOutputStream.
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("Filterfile.txt")); while (bis.available() > 0) System.out.print((char)bis.read());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(strFileName))); String str = "BufferedOutputStream Example"; bos.write(str.getBytes());............................... finally { //Close the BufferedOutputStream try { if (bufferedOutput != null) { bufferedOutput.flush(); bufferedOutput.close(); } }
DataInputStream and DataOnputStream :
The DataInputStream class enables you to read Java primitives from InputStream's instead of only bytes. You wrap an InputStream in a DataInputStream and then you can read primitives from it.
CHARACTER STREAM DATA HANDLING : (All byte stream classes extends 'Reader' and 'Writer'.)
Character streams works with the characters rather than the byte. In Java characters are stored by following the Unicode (allows a unique number for every character) conventions. In such kind of storage characters becomes the platform independent, program independent, language independent. Characters storage using Unicode convention makes the Java ready for internationalization and for this Java provides the Character stream I/O. Character stream I/O is helpful for internationalization because it automatically translated the internal format to and from the local character set.
Java IO's Reader and Writer work much like the InputStream and OutputStream with the exception that Reader and Writer are character based. They are intended for reading and writing text.
Reader and Writer :
The Reader is the baseclass of all Reader's in the Java IO API. Subclasses include a BufferedReader, PushbackReader etc.Notice, that while an InputStream returns one byte at a time, meaning a value between -128 and 127, the Reader returns a char at a time, meaning a value between 0 and 65535.
The Writer class is the baseclass of all Writer's in the Java IO API.
FileReader and FileWriter :
FileReader : The FileReader class makes it possible to read the contents of a file as a stream of characters. It works much like the FileInputStream except the FileInputStream reads bytes, whereas the FileReader reads characters. The FileReader is intended to read text, in other words. One character may correspond to one or more bytes depending on the character encoding scheme.The FileReader object also lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
FileWriter : This class is used to write to character files.Creation of a FileWriter is not dependent on the file already existing. FileWriter will create the file before opening it for output when you create the object. Its write() methods allow you to write character(s) or Strings to a file. FileWriters are usually wrapped by higher-level Writer objects such as BufferedWriters or PrintWriters, which provide better performance and higher-level, more flexible methods to write data.
File file = new File("fileWrite2.txt"); FileWriter fw = new FileWriter(file); for(int i=0;i<10;i++){ fw.write("Soham is Just Awesome : "+i); fw.flush(); } fw.close();
int c; FileReader fread = new FileReader("xanadu.txt"); FileWriter fwrite = new FileWriter("characteroutput.txt"); while ((c = fread.read()) != -1) fwrite.write(c);
BufferedReader and BufferedWriter :
A BufferedReader and a BufferedWriter act like BufferedOutputStream and BufferedInputStream, except they deal with reading and writing characters.As we mentioned, a BufferedWriter allows us to write to a buffer. It applies buffering to a character output stream, improving output efficiency by combining many small write requests into a single larger request.This class has an interesting additional method that makes Java code portable. Most of the time, a new line is represented by a \n, but it may not be in all operating systems. Because of this, the Java language adds a method called newLine(). Instead of outputting the character \n, you call newLine() and that outputs the appropriate new-line character for the particular operating system that you are running on. In most cases, this will be \n.
BufferedReader reader = new BufferedReader(new FileReader(inFile)); String line = reader.readLine(); while (line != null) { line = line.replaceAll("the", "JAVAJAVA") .toUpperCase (); System.out.println(line); line = reader.readLine() ; }
BufferedWriter writeMe = new BufferedWriter(new FileWriter(outFile)); int c; while ((c = reader.read()) != -1) writeMe.write(c);
RANDOM ACCESS FILES IN JAVA :
The RandomAccessFile class in the Java IO API allows you to move around a file and read from it or write to it as you please. You can replace existing parts of a file too. This is not possible with the FileInputStream or FileOutputStream.Few salient features are as follows :
- A RandomAccessFile employs an internal pointer that points to the next byte to read.
- This pointer is zero-based and the first byte is indicated by index 0.
- When first created, a RandomAccessFile points to the first byte.
- You can change the pointer's position by invoking the seek method.
- The skipBytes method moves the pointer by the specified number of bytes.
- If skipping offset number of bytes would pass the end of file, the internal pointer will only move to as much as the end of file.
- The skipBytes method returns the actual number of bytes skipped.
"r". Open for reading only.
"rw". Open for reading and writing. If the file does not already exist, RandomAccessFile creates file.
RandomAccessFile raf = new RandomAccessFile("c:\\temp\\RAFsample.txt", "rw"); raf.writeInt(1); raf.writeInt(22); raf.writeInt(333); raf.seek((2 - 1) * 4);// change the 2nd integer from 22 to 11 raf.writeInt(11); raf.seek(0); // go to the first integer int i = raf.readInt(); while (i != -1) { System.out.println(i); i = raf.readInt(); } raf.close();
FEW OTHER USEFUL EXAMPLES :
Few other examples that might help you guys.
Creating new Directory for writing :
File delDir = new File("deldir"); delDir.mkdir(); File delFile1 = new File(delDir, "delFile1.txt"); delFile1.createNewFile();
Reading a Directory Recursively :
public static ArrayList visitAllDirsAndFiles(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { listFil.add(dir.getAbsolutePath()+"\\"+children[i]); System.out.println(dir.getAbsolutePath()+"\\"+children[i]); visitAllDirsAndFiles(new File(dir, children[i])); } } return listFil; }
Reading from web-service and other HTTP responses :
DataInputStream in; if(ResponseCode != 200) in=new DataInputStream(conn.getErrorStream()); else in = new DataInputStream(conn.getInputStream()); String totData = ""; while( true ){ System.out.println( "Size = " + in.available()); if( in.available() == 0 ) break; byte[] data = new byte[in.available()]; in.read(data); totData += new String(data); Thread.sleep(500); in = new DataInputStream(conn.getInputStream()); } String content=new String(data);
Reading through "input" parameter from JSP (multi-part file upload):
String contentType=request.getContentType(); if((contentType!=null)||(contentType.indexOf("multipart/form-data")>0)) { DataInputStream in=new DataInputStream(request.getInputStream()); byte[] data = new byte[formDataLength]; String totData = ""; int byteRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength) { byteRead = in.read(data, totalBytesRead, formDataLength); totalBytesRead += byteRead; } //Convert the form data byte array into string String FormContentStr=new String(data);
While File and not Path?
ReplyDeleteAs you must have inferred from the post..the contents here pertain to java.io.*...I would be posting a separate article on java.nio.* package wherein I would surely use 'path' instead of 'file'....
DeleteI suggest using System.getProperty("file.separator") instead of the hardcoded "\" (which only works in Windows) in your Directory Traversal code sample. This will ensure the code is portable across Windows, MacOS and Linux.
ReplyDeleteI appreciate your feedback and yes..ideally we should use System.getProperty("file.separator") instead of hardcoding..But nevertheless , in this post I primarily wanted to highlight the File Handling APIs..Thanks for the comment though...
Delete