使用FileStream在Java中复制文件

使用FileStream在Java中复制文件,java,fileinputstream,fileoutputstream,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();

我想用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”

输出文件“输出”

输出文件中有许多额外的“^@”。
输入文件的大小为39字节。
输出文件的大小为1KB。

为什么输出文件中有许多额外的字符?

当调用
infle.read
时,返回值会告诉您要取回多少项。当您调用
outfile.write
时,您告诉它缓冲区已满,因为您没有存储从
读取
调用返回的字节数

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

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

您正试图将
1024
字节从文件复制到另一个文件。这样做行不通。尝试按文件大小读取

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

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

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

数组b[]的大小为1KB。附加字符“@”表示文件仍有未使用的空间。从技术上讲,您是在字节数组中复制文件,并在输出文件中写入but数组。这就是出现此问题的原因。

复制文件的最简单方法是调用单一方法
1.Java 7之前-来自库

2.在Java 7和8中

如果文件太大会发生什么?它可能会给您
java.lang.OutOfMemoryError
异常。在这种情况下,你仍然可以增加记忆虽然…谢谢,它真的帮助了我。
byte[] b = new byte[1024];
int len;
while((len = infile.read(b, 0, 1024)) > 0){
    outfile.write(b, 0, len);
}
FileInputStream infile = new FileInputStream("in");
FileOutputStream outfile = new FileOutputStream("out");

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

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