字节流输出输入--文件复制及输出

package cn.tedu.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

import javax.print.attribute.standard.OutputDeviceAssigned;

//测试文件复制练习
public class Test5_FileCopy {
public static void main(String[] args) {

String freompath = new Scanner(System.in).nextLine();
File from = new File(freompath);

String topath = new Scanner(System.in).nextLine();
File to = new File(topath);
copy2(from, to);//方案二

// copy1(from, to);//方案一
}

private static void copy2(File from, File to) {//方案二
try(
InputStream in = new BufferedInputStream(new FileInputStream(from));
OutputStream out= new BufferedOutputStream(new FileOutputStream(to));
)
{
int b = 0;
while((b=in.read())!=-1) {
out.write(b);
}
}catch(IOException e) {
e.printStackTrace();
}
}


private static void copy1(File from, File to) {//方案一
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(from));
out = new BufferedOutputStream(new FileOutputStream(to));
int b = 0;
while ((b = in.read()) != -1) {
out.write(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 3.释放资源--保证一定会被执行,放入finally块里
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}

}
}

posted @ 2020-07-20 11:29  tmuchen  阅读(109)  评论(0)    收藏  举报