使用FileStream在Java中复制文件

我想使用FileStream在Java中复制文件.
这是我的代码.

FileInputStream infile = new FileInputStream("in");
FileOutputStream outfile = new FileOutputStream("out");

byte[] b = new byte[1024];
while(infile.read(b, 0, 1024) > 0){
    outfile.write(b);
}

infile.close();
outfile.close();

我使用vim来查看我的文件.
输入文件“in”

Hello World1
Hello World2
Hello World3

输出文件“输出”

Hello World1
Hello World2
Hello World3
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@...

输出文件中有许多额外的’^ @’.
输入文件的大小为39字节.
输出文件的大小为1KB.
为什么输出文件中有很多额外的字符?

解决方法:

当您调用infile.read时,返回值会告诉您要返回的项目数.当你调用outfile.write时,你告诉它缓冲区被填满,因为你没有存储你从read调用中得到的字节数.

要解决此问题,请存储字节数,然后传递正确的数字来写:

byte[] b = new byte[1024];
int len;
while((len = infile.read(b, 0, 1024)) > 0){
    outfile.write(b, 0, len);
}
上一篇:IO流


下一篇:开源电子书阅读器 LibreraReader 编译环境与编译