怎么在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");
我们发现可以复制成功
关于怎么在Java中使用字节流实现图片音频的复制问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。