本篇文章小编给大家分享一下Java使用字节流实现图片音频的复制代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
Java字节流复制图片音频
java中的字节流可以实现文本的读入写入,当然也可以实现字节流对于图片的读入写入,就只需要写一个复制文本的字节输入输出流,然后在源文件和目标文件更换后缀图片就行了。
下面给出了source.png图片的路径,我们对其所对应的路径提供一个copysource.png的复制图片文件。
1.首先找到这两个文件的路径。如果写入的文本没有创建的话,会自动创建。
File source = new File("C:UsersLenovoDesktopcsdniotestsource.png");
File copysource = new File("C:UsersLenovoDesktopcsdniotestcopysource.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:UsersLenovoDesktopcsdniotestsource.png");
File copysource = new File("C:UsersLenovoDesktopcsdniotestcopysource.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:UsersLenovoDesktopcsdniotest林俊杰-修炼爱情(超清).mp4");
File copysource = new File("C:UsersLenovoDesktopcsdniotestcopy修炼爱情JJ.mp4");
我们发现可以复制成功
模拟极限越野
模拟极限越野开着大巴在各种奇葩路况里送乘客。山路弯道多得让人
模拟火车
模拟火车让你当回真正的火车司机,得先学会看信号灯、操作控制杆
可口的披萨美味的披萨
可口的披萨美味的披萨带您体验经营一家披萨店的乐趣。游戏画风温
定制虚拟偶像最新版
定制虚拟偶像最新版是一款超级经典有趣的日本模拟装扮类型的手游
病娇模拟器手机版正版(yandere simulator)
病娇模拟器最新版手游是一款萌妹二次元模拟游戏,玩家在游戏中可