Java字节流复制图片音频
java中的字节流可以实现文本的读入写入,当然也可以实现字节流对于图片的读入写入,就只需要写一个复制文本的字节输入输出流,然后在源文件和目标文件更换后缀图片就行了。
下面给出了source.png图片的路径,我们对其所对应的路径提供一个copysource.png的复制图片文件。

1.首先找到这两个文件的路径。如果写入的文本没有创建的话,会自动创建。
File source = new File("C:\\Users\\Lenovo\\Desktop\\csdn\\iotest\\source.png");
File copysource = new File("C:\\Users\\Lenovo\\Desktop\\csdn\\iotest\\copysource.png");
|
2.定义字节输入流,字节输出流
InputStream in = null;
OutputStream out = null;
|
3.通过字节输入流读入source.png文件的内容,在通过字节输出流将其输入到copysource.png中。
in = new FileInputStream(source);
out =new FileOutputStream(copysource);
byte[] bt = new byte[(int)source.length()];
int length = 0;
while( (length = in.read(bt))!=-1) {
out.write(bt,0,length);
}
|
4.关闭流
if(null!=in) {
try {
in.close();
}catch(IOException e) {
}
}
if(null!=out) {
try {
out.close();
}catch(IOException e) {
}
}
}
|
经过上述的代码,就可以将source.png的图片复制到copysource.png中了。这个时候就会发现该路径下多出了一张copysource.png的图片了。

以下是完整代码:
import java.io.*;
public class IOTest {
public static void main(String[]args) {
File source = new File("C:\\Users\\Lenovo\\Desktop\\csdn\\iotest\\source.png");
File copysource = new File("C:\\Users\\Lenovo\\Desktop\\csdn\\iotest\\copysource.png");
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(source);
out =new FileOutputStream(copysource);
byte[] bt = new byte[(int)source.length()];
int length = 0;
while( (length = in.read(bt))!=-1) {
out.write(bt,0,length);
}
}catch(IOException e) {
}finally {
if(null!=in) {
try {
in.close();
}catch(IOException e) {
}
}
if(null!=out) {
try {
out.close();
}catch(IOException e) {
}
}
}
System.out.println("复制成功");
}
}
|
和上面复制图片的代码一样,只需要修改文件路径,音频和视频都是可以复制的。
下面还是以上述的路径为例,给出一个后缀为mp4文件,我们将其通过代码复制一份,由上面的代码我们只需要修改文件路径的内容。
File source =new File("C:\\Users\\Lenovo\\Desktop\\csdn\\iotest\\林俊杰-修炼爱情(超清).mp4");
File copysource = new File("C:\\Users\\Lenovo\\Desktop\\csdn\\iotest\\copy修炼爱情JJ.mp4");
|
我们发现可以复制成功

|