Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

I am getting junk, when trying file copy  RSS feed

 
Kareem Qureshi
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I am trying to copy a existing file to a new file. Here is what i am doing
I am creating 2 File objects
File f = new File("c:"+"\\kareem"+"\\resume"+"\\Test.doc");
File x = new File("c:"+"\\kareem"+"\\resume"+"\\Resume.doc");
I am creating FileReader object and passing x
FileReader r = new FileReader(x);
I am creating a FileWriter Object and passing f
FileWriter w = new FileWriter(f);
And rest of the code is
int c;
while((c = r.read()) != -1)
{
w.write(c);
System.out.println(r.read());
}
r.close();
w.close();
}
catch(IOException e){}
}
It is executing and i am getting Test file but its size is half of the original file which is Word document, and contains junk in it.
Please clear this as i am very new to I/O programming. Thanks in advance
kareem
 
Zakaria Haque
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since word documents are binary format, you have to use binary streams(InputStream/OutputStream), not character streams(reader/writer).
 
Zakaria Haque
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is some untested code, which should serve your purpose
InputStream in = new BufferdInputStream(new FileInputStream("sourcefile"));
OutputStream out = new BufferedOutputStream(new FileOutputaStream("detination file"));
byte[] buffer = new byte[512];
while(true) {
int datLength = in.read(buffer);
if(dataLength == -1) {
break;
}
out.write(buffer,0,dataLength)
}
in.close();
out.flush();
out.close();
 
Kareem Qureshi
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Zakaria
I was under the impression that since word document contains characters, so character stream classes should work.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!