Java字节流代码复制文件

Java字节流代码复制文件

复制文件主要用到的是IO流的知识,不论是复制文本还是复制图片,道理都是一样的,只不过是改下后缀。
下面有几种复制文件的代码,亲测运行良好,希望能给各位带来帮助

假设要把D盘中的test.txt文件复制到E盘并重命名为hello.txt

单个字节流复制文本文件

public class Copy {

	public static void main(String[] args) throws Exception {
		copy();

	}

	private static void copy() throws Exception {
		// 创建输入流对象,并给出原文件位置
		FileInputStream fileInputStream = new FileInputStream("D:\\test.txt");
		// 创建输出流对象,并给出要复制到的位置
		FileOutputStream fileOutputStream = new FileOutputStream("E:\\hello.txt");
		int red ;
		// fileInputStream.read()该方法为读取数据,一次读取一个字节;
		// 如果字节读取完毕,则该方法输出结果为   -1;
		while((red=fileInputStream.read())!=-1) {
			//fileOutputStream.write  该方法为写入数据,一次写入一个数据
			fileOutputStream.write(red);
		}
		// 关闭输入流
		fileInputStream.close();
		// 关闭输出流
		fileOutputStream.close();
	
	}
}

此代码方法同上,只是利用了byte数组作为数据读入的缓冲区(缓冲区大小格式一般为[1024*n])

public class Copy {

	public static void main(String[] args) throws Exception {
		copy();

	}

	private static void copy() throws Exception {
		// 创建输入流对象,并给出原文件位置
		FileInputStream fileInputStream = new FileInputStream("D:\\test.txt");
		// 创建输出流对象,并给出要复制到的位置
		FileOutputStream fileOutputStream = new FileOutputStream("E:\\hello.txt");
		byte[] bytes = new byte[1024*10];
		int length ;
		// fileInputStream.read()该方法为读取数据,一次读取一组字节;
		// 如果字节读取完毕,则该方法输出结果为   -1;
		while((length=fileInputStream.read(bytes))!=-1) {
			//fileOutputStream.write  该方法为写入数据,一次写入一组数据
			fileOutputStream.write(bytes,0,length);
		}
		// 关闭输入流
		fileInputStream.close();
		// 关闭输出流
		fileOutputStream.close();
	
	}
}

利用字节缓冲流读取和写入数据

字节缓冲流通过一次读取写入一定长度的数据,而减少了对硬盘的存取,可以增加文件的存取效率

public class Copy {

	public static void main(String[] args) throws Exception {
		copy();

	}

	private static void copy() throws Exception {
		// 创建输入流对象,并给出原文件位置
		FileInputStream fileInputStream = new FileInputStream("D:\\test.txt");
		// 创建写入缓冲对象
		BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
		// 创建输出流对象,并给出要复制到的位置
		FileOutputStream fileOutputStream = new FileOutputStream("E:\\hello.txt");
		//创建写出缓冲对象
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
		byte[] bytes = new byte[1024*10];
		int length ;
		// bufferedInputStream.read()该方法为读取数据,一次读取一个字节;
		// 如果字节读取完毕,则该方法输出结果为   -1;
		while((length=bufferedInputStream.read(bytes))!=-1) {
			//bufferedOutputStream.write  该方法为写入数据,一次写入一组数据
			bufferedOutputStream.write(bytes,0,length);
		}
		// 关闭输入流
		bufferedInputStream.close();
		// 关闭输出流
		bufferedOutputStream.close();
	
	}
}

上面的代码主要是字节流复制文件,如果其中有任何错误,欢迎大家指出,一定积极改正,共同学习,共同进步。

猜你喜欢

转载自blog.csdn.net/weixin_47405768/article/details/107869523