Sample code is :-
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class CopyBytes {
public static void main(String [] args){
CopyBytes obj = new CopyBytes();
File file = new File("/home/mount/Data/JAVA/xanadu.bak");
obj.copyBytes(file);
}
public void copyBytes(File ifile){
FileInputStream reader = null;
FileOutputStream output =null;
int c=0;
try{
reader = new FileInputStream(ifile);
output = new FileOutputStream("outfile");
while((c = reader.read()) != -1)
{
System.out.print(c);
output.write(c);
}
System.out.println();
}
catch(FileNotFoundException fnfex){
fnfex.getMessage();
fnfex.printStackTrace();
}
catch(IOException ioex){
ioex.getMessage();
ioex.printStackTrace();
}
finally{
if(reader !=null)
{
System.out.println("Closing the Stream");
try{
reader.close();
System.out.println("Closed the Streams");
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
}
else{
System.out.println("Stream not open");
}
}
}
}
Contents of the xanadu.bak are as follows:-
buffer@ankit:/home/mount/Data/JAVA/practice/src/fileio.bytestreams.com$ cat /home/mount/Data/JAVA/xanadu.bak
IA
When above code is run;it gives following output:
buffer@ankit:/home/mount/Data/JAVA/practice/src/fileio.bytestreams.com$ java CopyBytes
736510
Closing the Stream
Closed the Streams
whereas i should get
7365
Closing the Stream
Closed the Streams
The file to which I am writing is perfectly fine. Please provide your valuable inputs.
The last character printed is
10d, or0x0A. That’s a newline character. Other combinations like0x0D 0x0Aor the reverse could happen on other platforms.A lot of editors add a newline at the end of files if there isn’t one, and that’s what you’re seeing.
Use something like
hexdumpto ascertain what your file really contains.You code works pretty well for that too 🙂