Skip navigation

When we develop an application, sometimes we need to read a file from disk. Not only character based files, but also byte/binary based files. To read/write character based files we use Writer and Reader class hierarchy, to read byte/binary based files we use InputSteam and OutputStream class hierarchy.

This article will show how to read binary files such as EXE, PDF, and make a copy of that file on different location on disk. We will open the file, read byte by byte, and write all the bytes we get to make a copy of that file.

I use three different way to get the bytes from the file as far as i know. I dont know which one is the best based on the performance or algorithm :p.

(Way 1)


File file = new File(PATH_TO_FILES);

fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));

fos = new FileOutputStream(DESTINATION_PATH_AND_FILE_NAME);
dos = new DataOutputStream(new BufferedOutputStream(fos));

byte b;
try{
	while(true){
		b = (byte) dis.readByte();

		dos.write(b);
	}
}
catch(EOFException e){
	System.err.println("Finish read end of file...");
}
finally{
        dos.close();
}

(Way 2)

File file = new File(PATH_TO_FILES);

fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));

fos = new FileOutputStream(DESTINATION_PATH_AND_FILE_NAME);
dos = new DataOutputStream(new BufferedOutputStream(fos));

byte[] b = new byte[(int) file.length()];

for(int i=0; i<b.length-1; i++)
{
	b&#91;i&#93; = dis.readByte();
}

dos.write(b);
dos.close();
&#91;/sourcecode&#93;</pre>

<strong>(Way 3)</strong>
<pre>
File file = new File(PATH_TO_FILES);

fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));

fos = new FileOutputStream(DESTINATION_PATH_AND_FILE_NAME);
dos = new DataOutputStream(new BufferedOutputStream(fos));

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[200];

while(true){
	int length = dis.read(b);

	System.out.println("read : " + length);

	if (length < 0) {
		break;
	}

	if(length > 0){
		baos.write(b, 0, length);
	}

}

dos.write(baos.toByteArray());
dos.close();

(Full source code)

/**
 * @author	: gardiary
 * @Waktu	: Jul 28, 2008, 4:33:14 PM
 *
 * StreamSample.java
 */
package test.filehandling;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StreamSample {
	private File file;
	private FileInputStream fis;
	private FileOutputStream fos;
	
	private DataInputStream dis;
	private DataOutputStream dos;
	
	public StreamSample()
	{
		file = new File("input/ajax-tutorial.pdf");		
	}
	
	public static void main(String args[])
	{
		StreamSample app = new StreamSample();
		
		app.copyFile1();
		System.out.println("Done copy file 1...");
		
		app.copyFile2();
		System.out.println("Done copy file 2...");
		
		app.copyFile3();
		System.out.println("Done copy file 3...");
		
		try{
			app.dis.close();
			app.fis.close();
		}
		catch(IOException ioe){
			ioe.printStackTrace();
		}
	}
	
	// copy file first way
	public void copyFile1()
	{
		openFileInput();
		
		try{
			fos = new FileOutputStream("output/copy-of-ajax-tutorial-1.pdf");
			dos = new DataOutputStream(new BufferedOutputStream(fos));
			
			byte b;
			try{
				while(true){
					b = dis.readByte();
					
					dos.write(b);
				}
				
			}
			catch(EOFException e){
				System.err.println("Finish read end of file...");
			}
			
		}
		catch(IOException e){
			System.err.println("IOException...1");
		}
		finally{
			closeOutputStream(dos);
			closeOutputStream(fos);
		}
	}
	
	// copy file second way
	public void copyFile2()
	{
		openFileInput();
		
		try{
			fos = new FileOutputStream("output/copy-of-ajax-tutorial-2.pdf");
			dos = new DataOutputStream(new BufferedOutputStream(fos));
			
			byte[] b = new byte[(int) file.length()];
			
			for(int i=0; i<b.length-1; i++)
			{
				b&#91;i&#93; = dis.readByte();
			}
			
			dos.write(b);
		}
		catch(IOException e){
			System.err.println("IOException...2");
			e.printStackTrace();
		}
		finally{
			closeOutputStream(dos);
			closeOutputStream(fos);
		}
	}
	
	// copy file third way
	public void copyFile3()
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte&#91;&#93; b = new byte&#91;200&#93;;
	
		openFileInput();
		
		try{
			fos = new FileOutputStream("output/copy-of-ajax-tutorial-3.pdf");
			dos = new DataOutputStream(new BufferedOutputStream(fos));
			
			while(true){
				int length = dis.read(b);
				
				System.out.println("read : " + length);
				
				if (length < 0) {
			        break;
				}
				
				if(length > 0){
					baos.write(b, 0, length);
				}
								
			}
			
			dos.write(baos.toByteArray());
		}
		catch(IOException e){
			System.err.println("IOException...3");
		}
		finally{
			closeOutputStream(dos);
			closeOutputStream(fos);
		}
	}
	
	// open file for input
	public void openFileInput()
	{
		try{
			fis = new FileInputStream(file);
			dis = new DataInputStream(new BufferedInputStream(fis));
		}
		catch(FileNotFoundException e){
			System.err.println("File Not Found...!");
		}
	}
	
	// close output stream
	public void closeOutputStream(OutputStream os)
	{
		try{
			os.close();
		}
		catch(IOException ioe){
			System.err.println("Exception closing output stream");
		}
		
	}
}

18 Comments

  1. good solution to a common problem. I would recommend your writing to any developer.

    Please let me know if you need work.

    Best Regards,

    David Barrett

  2. Thanks for the comment.

    How can I contact you?

    Regards,
    Gardiary

  3. /* This is a better and simpler approach to read and write file in java*/

    import java.io.*;

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

    FileReader fr = new FileReader(“inputfile.txt”); // use any filename and contents
    BufferedReader br = new BufferedReader(fr);
    int inputline;
    FileWriter fw = new FileWriter(“outputfile.txt”); //use any filename

    while((inputline =br.read()) !=-1) // check to see if the file has ended
    {
    fw.flush();
    fw.write(inputline);

    }
    fr.close();
    fw.close();
    }catch (IOException e){}; /* Program by Sumish Darak*/ } }

  4. Thanks it works for me

  5. its working Nice

  6. Thank you, very much. You’ve saved me.

  7. I actually want to take note of this blog post, “Using Stream class to read and
    write bytes of files Gardiary’s HOT Weblog” on my web site. Would you care in case Ido? Regards -Hermelinda

  8. These are really great ideas in on the topic of blogging.

    You have touched some pleasant things here. Any way keep up wrinting.

  9. Everything is very open with a clear clarification
    of the issues. It was definitely informative.
    Your site is very helpful. Thanks for sharing!

  10. Greetings! I’ve been reading your blog for a long time now and finally got the bravery to go ahead and give you a shout out from Houston Texas! Just wanted to say keep up the fantastic work!

  11. Howdy! I know this is somewhat off topic but I was
    wondering which blog platform are you using for this website?
    I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be great if you could point me in the direction of a good platform.

  12. I completely concur along with your publish. I have lived here for nearly 3 many years now
    and also you are so correct in regards to the misleading numbers.
    Entertaining spot to do issues and party, but boyfriend and partner are couple of
    and far amongst. My one friends have told me stories
    which have produced me believe 2 times about keeping here.

    Once my agreement is up in 17 months, I am outta right here.

  13. Hey there would you mind sharing which blog platform you’re working with? I’m looking to
    start my own blog in the near future but I’m having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique.

    P.S My apologies for getting off-topic but I had to ask!

  14. I am incredibly involved within this case. Where can I find extra
    information on this? Or, when you don’t pursue this additional here.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: