java 实现文件复制demo

时间:2022-10-11 20:50:43

1、先说一下java字节流和字符流的区别。
  java字节流主要操作byte类型数据,以byte数组为准,主要操作类是OutputStream和InputStream类。所有与字节操作有关的子类都是直接或者间接继承这两个类。
  在java程序中一个字符等于两个字节,那么java提供了Reader和Writer两个专门操作字符流的类。
实际上字节流在操作时本身不会用到缓冲区(内存),是文件本身直接操作的,而字符流在操作时使用了缓冲区,通过缓冲区再操作文件
java 实现文件复制demo
2、直接上代码
下面分别实现了使用字节流和字符流读文件:

//使用InputStream 字节流读取数据
public static void input() throws Exception{
//第一步:使用File类找到一个文件
File f = new File("D:"+File.separator+File.separator+"test.txt");
//第二步:通过子类实例化父类
InputStream input = new FileInputStream(f);
//第三步:进行读操作
byte[] b = new byte[(int)f.length()];
int len = input.read(b);
//第四步:关闭输出流
input.close();
System.out.println("内容为:"+new String(b));

// 第二种方式读取
// int len = 0;
// byte[] b = new byte[1024];
// int temp = 0;
// while((temp=input.read())!=-1)){
// b[len] = (byte)temp;
// len++;
// }
// input.close();
}

//使用Reader字符流读取数据
public static void reader() throws Exception{
//第一步:使用File类找到一个文件
File f = new File("D:"+File.separator+File.separator+"test.txt");
//第二步:通过子类实例化父类
Reader read = new FileReader(f);
//第三步:进行读操作
char[] c = new char[(int) f.length()];
read.read(c);
//第四步:关闭输出流
read.close();
System.out.println(new String(c));
}

下面分别实现了使用字节流和字符流写文件:

//使用OutputStream 字节流写数据
public static void output() throws Exception {
//第一步 :使用File类找到一个文件
File f = new File("d:"+File.separator+File.separator+"test.txt");
//第二步:通过子例实例化父类对象
OutputStream out = new FileOutputStream(f,true);
//第三步:进行写操作
String str = "hello world" ; //准备一个字符串
byte[] b = str.getBytes(); //只能输出byte数组,所以将字符串变为byte数组
out.write(b); //将内容输出,保存文件
//关闭输出流
out.close();

// 第二种方式写入
// //用write(int i)的方式写入文件内容
// for(int i=0;i<b.length;i++){
// out.write(b[i]);
// }
}

//使用Writer字符流写数据
public static void write() throws Exception{
//第一步:使用File类找到一个文件
File f = new File("d:"+File.separator+File.separator+"test.txt");
//第二步:通过子例实例化父类对象
Writer out = new FileWriter(f);
//第三步:进行写操作
String str = "Hello world";
out.write(str);
//第四步:关闭输出流
out.close();
}

3、用字节流实现文件复制

package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Copy {
public static void main(String[] args) throws Exception{
if(args.length!=2){
System.out.println("输入的参数不正确");
System.out.println("例;java Copy 源文件路径 目标文件路径");
System.exit(1);;
}
File f1 = new File(args[0]);
File f2 = new File(args[1]);
if(!f1.exists()){
System.out.println("源文件不存在");
System.exit(1);
}
InputStream input = new FileInputStream(f1) ;
OutputStream output = new FileOutputStream(f2);
int temp = 0;
try{
while((temp=input.read())!=-1){
output.write(temp);
}
System.out.println("复制完成");
}catch(Exception e){
e.printStackTrace();
System.out.println("复制失败!");
}
input.close();
output.close();
}
}