示例代码是:-
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
我正在写入的文件完全没问题。请提供您的宝贵意见。
打印的最后一个字符是 10
d,即 0x0A
。这是一个换行符。其他组合(如0x0D 0x0A
或相反)可能会在其他平台上发生。
,许多编辑器会在文件末尾添加一个换行符,这就是您所看到的。
使用类似 hexdump
的东西来确定您的文件真正包含的内容。
你的代码也很好用:-)