Connecting Tech Pros Worldwide Forums | Help | Site Map

How to copy an image file.

Newbie
 
Join Date: Jul 2008
Posts: 11
#1: Aug 11 '08
Hello friends,
I want to copy files of extensio .bmp , .png, .tif , etc.

when I execute the following code i get errors in the file copied.

FileReader fr=new FileReader("D:/image.bmp");
BufferedReader br=new BufferedReader(fr);
FileReader fw=new FileWriter("D:/copyImage.bmp");
String s;
while((s=br.readLine())!=null)
{
fw.write(s);
fw.write(System.getProperty("line.separator"));
}

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Aug 11 '08

re: How to copy an image file.


Don't use Readers and Writers for binary files; use InputStreams and OutputStreams
instead. The first pair handles characters and do quite a bit of conversion (UTF-8
etc.) The second pair handles simple bytes and don't do anything with them.

kind regards,

Jos
Needs Regular Fix
 
Join Date: Nov 2007
Location: Cebu City, Philippines
Posts: 511
#3: Aug 11 '08

re: How to copy an image file.


You may also try FileChannel class together with FileInputStream and FileOutputStream.
BigDaddyLH's Avatar
Moderator
 
Join Date: Dec 2007
Location: Kelowna, BC Canada
Posts: 1,212
#4: Aug 11 '08

re: How to copy an image file.


Note, by the way, there's nothing special about this being an "image" file. You question was general to any binary file: for example, how to copy .class files.
Newbie
 
Join Date: Jul 2008
Posts: 11
#5: Aug 12 '08

re: How to copy an image file.


Thanks for your guidance.
My problem for copying images is solved.
I had used this code for doing that.

FileInputStream fis=new FileInputStream(new File("D:/image.bmp"));
FileOutputStream fos=new FilePutputStream(new FIle("D:/copyImage.bmp"));
int c;
while((c=fis.read())!=-1)
{
fos.write(c);
}

But one more problem arises. The Speed is very slow. When I use this to copy more than 1000-1200 files i.e. more than 200mb It takes around 4-5 min.
spending this much time is not feasible for me.

Is there any other way by which copying of files becomes faster.

Moiz
BigDaddyLH's Avatar
Moderator
 
Join Date: Dec 2007
Location: Kelowna, BC Canada
Posts: 1,212
#6: Aug 12 '08

re: How to copy an image file.


That way will be painfully slow -- you are copying the file directly, one byte at a time. Take a look at the InputStream/OutputStream methods that take an array of bytes. 8K is a good array size -- your code should be 8 thousand times faster!

Sukatoa's suggestion to use file channels is excellent as well. Did you follow his links and read?
Reply