【Java】InputStream,OutputStream,文件,图片的复制操作

相关其他博客:
IO体系
File类介绍
Writer,Reader

InputStream

java.lang.Object
java.io.InputStream

public abstract class InputStream
extends Object
implements Closeable

test文本内容为: hello world!黄骏捷

		File file = new File("test.txt");
		//根据文件对象创建文件输入流对象
		InputStream in = new FileInputStream(file);
		
		for(int i=0;i<file.length();i++) {
			int a = in.read();
			System.out.print((char)a);
		}
		System.out.println();
		
		for(int i=0;i<file.length();i++) {
			int a = in.read();
			System.out.print(a);
		}
		
		//关闭资源
		in.close();

//输出
hello world!??????

将其改进
一次读入一个字符数组

		File file = new File("test.txt");
		InputStream in = new FileInputStream(file);
		int length=0;
		byte [] bt = new byte[1024];
		while( (length = in.read(bt))!=-1){
			String str = new String(bt,0,length);
			System.out.println(str);
		}
//输出
hello world!黄骏捷

OutputStream

java.lang.Object
java.io.OutputStream

public abstract class OutputStream
extends Object
implements Closeable, Flushable

OutputStream out = new FileOutputStream(file,true);
再次运行不会再覆盖之前的内容,而是追加内容。

File file = new File("test.txt");
		if(!file.exists()) {
			file.createNewFile();
		}
		
		//根据文件对象创建文件字节输出流对象
		//OutputStream out = new FileOutputStream(file);
		OutputStream out = new FileOutputStream(file,true);
		String str="helloworld";
		
		for(int i=0;i<str.length();i++) {
			out.write(str.charAt(i));
		}
		
		out.close();
//输出
//运行1次
helloworld
//运行3次
helloworldhelloworldhelloworld

将字符串转为字节数组,输出中文就不会出现乱码

File file = new File("test.txt");
		//部分平台如果没有目标文件,会自动创建
		OutputStream out = new FileOutputStream(file,true);//追加
		String str = "你好!!";
		
		//将字符串转换为字节数组
		byte [] bt = str.getBytes("UTF-8");
		out.write(bt);	//一次性写入整个字节
		out.close();

文件复制操作

我只写主要操作了

		//原文件对象
		File source = new File("test1.txt");
		//目标文件对象
		File dest = new File("test2.txt");
		if(!dest.exists()) {
			dest.createNewFile();
		}
	//根据源文件对象创建字节输入流对象
	in=new FileInputStream(source);
	//根据目标文件对象创建字节输出流对象
	out=new FileOutputStream(dest);
	byte []bt = new byte[1024];
	int length=0;
	while( (length=in.read(bt))!=-1) {
	//一次性写入文件
	out.write(bt,0,length);
	}

运行前
在这里插入图片描述
在这里插入图片描述
运行后
在这里插入图片描述

图片复制操作

		//原文件对象
		File source = new File("C:\\Users\\27266\\Desktop\\1.png");
		//目标文件对象
		File dest = new File("C:\\Users\\27266\\Desktop\\2.png");
		if(!dest.exists()) {
			dest.createNewFile();
		}
		
		InputStream in = null;
		OutputStream out = null;
		
		in = new FileInputStream(source);
		out = new FileOutputStream(dest);		
		
		byte []bt = new byte[1024];
		int length=0;
		while(	(length = in.read(bt)) !=-1) {
			//一次性写入文件中
			out.write(bt,0,length);
		}
		
		if(null!=out) {
			out.close();
		}
		
		if(null!=in) {
			in.close();
		}

在这里插入图片描述

发布了66 篇原创文章 · 获赞 45 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ACofKing/article/details/90246032