The moose likes I/O and Streams and the fly likes I am getting junk, when trying file copy Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Reply Bookmark "I am getting junk, when trying file copy" Watch "I am getting junk, when trying file copy" New topic
Author

I am getting junk, when trying file copy

Kareem Qureshi
Ranch Hand

Joined: Mar 14, 2002
Posts: 102
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

Joined: Jan 02, 2002
Posts: 60
since word documents are binary format, you have to use binary streams(InputStream/OutputStream), not character streams(reader/writer).


tobe bondhu nouka bherao<br />shonabo gaan aj shara raat
Zakaria Haque
Ranch Hand

Joined: Jan 02, 2002
Posts: 60
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

Joined: Mar 14, 2002
Posts: 102
Thanks, Zakaria
I was under the impression that since word document contains characters, so character stream classes should work.
 
IntelliJ Java IDE
 
subject: I am getting junk, when trying file copy
 
Threads others viewed
IO package
FileReader question
FileWriter
How to create a file in specified directory
Passing References
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com