示例代码是: -
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");
}
}
}
}
内容xanadu.bak
如下:-
buffer@ankit:/home/mount/Data/JAVA/practice/src/fileio.bytestreams.com$ cat /home/mount/Data/JAVA/xanadu.bak
IA
当上面的代码运行时;它给出以下输出:
buffer@ankit:/home/mount/Data/JAVA/practice/src/fileio.bytestreams.com$ java CopyBytes
736510
Closing the Stream
Closed the Streams
而我应该得到
7365
Closing the Stream
Closed the Streams
我正在写入的文件非常好。请提供您宝贵的意见。