使用FileStream在Java中复制文件

Lar*_* Lu 3 java fileinputstream fileoutputstream

我想使用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();
Run Code Online (Sandbox Code Playgroud)

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

Hello World1
Hello World2
Hello World3
Run Code Online (Sandbox Code Playgroud)

输出文件"输出"

Hello World1
Hello World2
Hello World3
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@...
Run Code Online (Sandbox Code Playgroud)

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

das*_*ght 5

当您致电时infile.read,返回值会告诉您要回收的物品数量.当你调用时outfile.write,你告诉它缓冲区被填满,因为你没有存储从read调用中返回的字节数.

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

byte[] b = new byte[1024];
int len;
while((len = infile.read(b, 0, 1024)) > 0){
    outfile.write(b, 0, len);
}
Run Code Online (Sandbox Code Playgroud)