文章目录:
错误还原:
近期在回顾Java基础到iIO流时,自己实现一段小Demo版本的需求,就是先读取本地.
JPG 格式的文件到另外一个盘符,根据字节流来实现的。
先写出一个基础版本的,接下来在基础版面本上进行优化:
/**
* 使用IO 字节流 读取 本地非文本文件,并复制到另外一个敌方
*/
public class FileInputOutPutStream {
public static void main(String[] args){
//创建文件读取流
FileInputStream stream = null;
FileOutputStream stream2 = null;
try {
//需要赋值的图片
stream = new FileInputStream(new File("E:\\人物老师头像.jpg"));
//复制到目的地
stream2 = new FileOutputStream(new File("E:\\人物老师头像2.jpg"));
// 复制过程
byte[] bytes = new byte[5];
int len ;
while ((len = stream.read(bytes)) !=-1){
stream2.write(bytes,0,len);
}
System.out.println("复制成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream !=null){
//关闭流
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (stream2 !=null){
try {
stream2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
迭代本,其实下下面这个更像是一个工具类,我们在用着的时候,直接调用即可:
/**
* 相当于工具类,优化版本
* @param srcPath
* @param destPath
*/
// @Test
public void CopyFile(String srcPath, String destPath){
//创建文件读取流
FileInputStream stream = null;
FileOutputStream stream2 = null;
try {
//需要赋值的图片
stream = new FileInputStream(new File(srcPath));
//复制到目的地
stream2 = new FileOutputStream(new File(destPath));
// 复制过程
byte[] bytes = new byte[1024];
int len ;
while ((len = stream.read(bytes)) !=-1){
stream2.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream !=null){
//关闭流
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (stream2 !=null){
try {
stream2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
小总结:
-
其实优化的敌方就是在形参列表中把我们常用的,并且时经常改变的输入、输出路径,当作形参列表。
-
上面仔细观察就是在main 方法上面有一个注解掉的@Test注解,就是它导致,在完成并测试的时候,导致一致报错此方法,
-
在测试类里有形参时,不能有Test 注解。不然就会爆如下错误:
在优化版基础上进行测试:看看效果
@Test
public void TestCopyFile(){
long start = System.currentTimeMillis();
String srcPath ="E:\\人物老师头像.jpg";
String destPath = "E:\\人物老师头像4";
CopyFile(srcPath,destPath);
long end = System.currentTimeMillis();
if (destPath !=null){
System.out.println("输出成功~耗费时间为:"+(end-start));
}else if (srcPath ==null){
System.out.println("没有读取到文件");
}
}
}
总结:
查看复制路径存在了已经:并且是一样大小,有一个小注意点就是注意在复制到目的地时要在后缀填写对应的文件格式,不然文件打不开啦。我i这个复制的是图片,当然字节流也可以复制视频,若实现复制视频,直接在最后一个测试类内写对应的路径即可,好这个问题,就先告一段落。。。