字节多功能既可以复制文件 还可以辅助图片.jgp
public class TestCopyFile {
public static void main(String[] args) {
//1.提示并接收用户输入
System.out.println("请输入源文件路径");//被复制的那个文件
String f = new Scanner(System.in).nextLine();
System.out.println("请输入新文件路径");//被复制的那个文件
String t = new Scanner(System.in).nextLine();
//2.调用创建好的自定义方法完成文件复制
ZJCopy(f, t);
private static void ZJCopy(String f, String t) {
//1.定义在整个方法都生效的局部变量,注意手动初始化,引用类型默认为null
InputStream in = null;
OutputStream out = null;
//2.由于代码可能会发生异常所以需要编写 ,try-catch-finally结构
try {
in = new BufferedInputStream(new FileInputStream(f));
out = new BufferedOutputStream(new FileOutputStream(t));
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
System.out.println("恭喜你复制成功");
} catch (Exception e) {
System.out.println("很抱歉文件复制失败");
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字符多功能只可以复制文件
public class TestCopyFile {
public static void main(String[] args) {
//1.提示并接收用户输入
System.out.println("请输入源文件路径");//被复制的那个文件
String f = new Scanner(System.in).nextLine();
System.out.println("请输入新文件路径");//被复制的那个文件
String t = new Scanner(System.in).nextLine();
//2.调用创建好的自定义方法完成文件复制
ZFCopy(f, t);
//利用字符流完成文件复制案例
private static void ZFCopy(String f, String t) {
Reader in = null;
Writer out = null;
try {
in = new BufferedReader(new FileReader(f));
out = new BufferedWriter(new FileWriter(t));
//4.那这流对象以后,就可以使用流对象来完成业务了
//4.1定义变量用来保存读到的数据
int b;
//4.2循环读取源文件,直接返回值为-1,说明没有数据,在结束循环
while ((b = in.read()) != -1) {
//4.3将本轮循环中读到的数据写入新文件中
out.write(b);
}
System.out.println("恭喜你文件复制成功");
} catch (Exception e) {
System.out.println("很抱歉文件复制失败!");
e.printStackTrace();
} finally {
/*关流是有顺序的:如果有多个流,最后创建的流最先关闭
* 多条关流语句需要各自try-catch*/
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}