学习记录分享(IO框架总结)

1.用字节流复制一张图片

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestIO {

	public static void main(String[] args) throws IOException {
		//将指定图片,上传一份到项目里来!
		
		//文件时在存储设备中的--》读到程序中来--》写入到存储设备种
		//输入流
		FileInputStream fis = new FileInputStream("C:\\Users\\87980\\Desktop"
				+ "\\360截图20200316150348671.jpg");
		//3317456 ---- 4M 够
		byte[] cache = new byte[1024*1024*4];
		int len = 0;//代表每次读到的字节
		FileOutputStream fos = new FileOutputStream("E:\\qianfengjava\\day31\\wo.jpg");
		while((len = fis.read())!=-1) {//只要不读到-1
			fos.write(len);//读多少写多少
		}
		
		
		//释放资源!
		fis.close();
		fos.close();

	}

}

2.对象实例化

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Arrays;

public class TestObjectStream {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		OutputStream os = new FileOutputStream("E:\\qianfengjava\\day31\\obj.txt");
		ObjectOutputStream oos = new ObjectOutputStream(os);
		
//		oos.writeInt(30);//把基本数据类型的数据写入到文件里以数据的形式存储(块数据)
//		oos.writeDouble(3.5);
//		oos.writeBoolean(true);
//		oos.flush();
		//------------
		InputStream is = new FileInputStream("E:\\qianfengjava\\day31\\obj.txt");
		ObjectInputStream ois = new ObjectInputStream(is);
		
//		int result = ois.read();
//		int result = ois.readInt();//必须读相对应的类型,写的什么类型就读什么类型
//		System.out.println(result);
		Object o = ois.readObject();//下一个读到的3.5不是一个Object,所以报错
//		System.out.println(o);
		
		
		Student stu = new Student("张三",12,"男",100d,new Address("北京","123456"),new int[] {1,2,3});
		Student stu2 = new Student("李四",16,"男",100d,new Address("北京","123456"),new int[] {1,2,3});
		Student stu3 = new Student("王五",20,"男",100d,new Address("北京","123456"),new int[] {1,2,3});
		oos.writeObject(stu);//对象写入
		oos.writeObject(stu2);//对象写入
		oos.writeObject(stu3);//对象写入
		oos.flush();
//		Object obj = ois.readObject();
//		Student s = (Student)obj;
//		System.out.println(obj);
//		System.out.println(s.name);
//		
//		Object obj2 = ois.readObject();
//		Student s2 = (Student)obj2;
//		System.out.println(obj2);
//		System.out.println(s2.name);
//		
//		Object obj3 = ois.readObject();
//		Student s3 = (Student)obj3;
//		System.out.println(obj3);
//		System.out.println(s3.name);
		
//		Object obj4 = ois.readObject();//对象没了,读到了末尾
//		Student s4 = (Student)obj4;
//		System.out.println(obj4);
//		System.out.println(s4.name);
		
		while(true) {
			try {
				Object obj1 = ois.readObject();
				System.out.println(obj1.toString());
			}catch(Exception e) {
				//到达文件末尾  获得EOFException 就停止循环
				break;
			}
		}
		//static 依旧是属于类的,会影响序列化

	}

}
//对象自身要支持序列化
//属性也要支持序列化,String是直接的,Integer和Double是间接的,因为它们有一个共同的父类Number实现了Sreializable接口
class Student implements Serializable{//实现了此接口,对象才可以序列化
	String name;
	Integer age;
	String sex;
	Double score;
	transient Address add;//transient修饰的属性不参与序列化
	//数组:基本数据类型可以序列化
	int[] nums = new int[3];
	//引用数据类型必须实现Serializable接口
	
	public Student(String name, Integer age, String sex, Double score, Address add, int[] nums) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.score = score;
		this.add = add;
		this.nums = nums;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", sex=" + sex + ", score=" + score + ", nums="
				+ Arrays.toString(nums) + "]";
	}
	
	
}
class Address implements Serializable{
	String position;
	String zipCode;
	public Address(String position, String zipCode) {
		super();
		this.position = position;
		this.zipCode = zipCode;
	}
	@Override
	public String toString() {
		return "Address [position=" + position + ", zipCode=" + zipCode + "]";
	}
	
	
}

3.输入字节流

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestFileInputStream {

	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("target.txt");
		
		//int n = fis.read();//一次读一个字节
		//System.out.println((char)n);
		
		//读到-1,就代表到达了文件的末尾!
//		while(true) {
//			int n = fis.read();//一次读一个字节
//			if(n==-1) {//文件末尾
//				break;//停止读的操作
//			}
//			System.out.println((char)n);
//		}
		
		byte[] bytes = new byte[4];//该数组作为读取时的存储
		while(true) {
			int count = fis.read(bytes);//每次读取到的有效字节个数
			if(count == -1) {
				break;
			}
			//读多少个,打印多少个!
			for(int i=0;i<count;i++) {
				System.out.print((char)bytes[i]);
			}
			System.out.println("\n");
		}
	}

}

4.输出字节流

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestOutputStream {

	public static void main(String[] args) throws IOException{
		
		//1.输出字节流OutputStream
		//2.输出字节节点流,具有实际传输数据的功能(文件路径,boolean append) true代表追加,不覆盖
		//路径正确  但是文件不存在,则会自动创建一个文件
		//绝对路径:"E:\\target.txt"  必须存在!
		//相对路径:"Files\\target.txt" 与上一种形式等价。相对于当前项目的路径下,寻找该路径和文件
		FileOutputStream fos = new FileOutputStream("E:\\qianfengjava\\day31\\target.txt");
		FileInputStream fis = new FileInputStream("E:\\qianfengjava\\day31\\target.txt");
		
		//String s = "你";
		
		//byte[] bs = s.getBytes();
		//System.out.println(bs[0]+"\t"+bs[1]);
		//fos.write(bs);
		
		fos.write(65);  //输出单个字节
		fos.write(66);
		fos.write(67);
		fos.write('D');
		
		byte[] bytes = new byte[] {65,66,67,68,69,70,'G'};
		
		fos.write(bytes);//一次输出一组字节!
		//字节数组     起始下标     长度
		fos.write(bytes,1,3);
		//ABCDABCDEFGBCD
		
		System.out.println((char)fis.read());//读取到A
		System.out.println((char)fis.read());//读取到B
		byte[] b = new byte[10];
		System.out.println(fis.read(b));//返回值为数组中有效字符个数
		System.out.println(fis.read(b));//返回值为数组中有效字符个数
		System.out.println((char)b[0]);//
		System.out.println((char)b[1]);//
		System.out.println((char)b[2]);//
		System.out.println((char)b[3]);//
		System.out.println((char)b[4]);//
		
		byte[] b2 = new byte[10];
		System.out.println(fis.read(b2,1,3));//继续按顺序读取fis节点输入流中的数据,读取到的字节数
											//据放入到b2数组,从下标1开始,长度为3,返回值为有效字节数(2,因为放入C,D
											//两个字符后没有了)
		System.out.println(b2[0]);//0
		System.out.println((char)b2[1]);//C
		System.out.println((char)b2[2]);//D
		System.out.println(b2[3]);//0
		

	}

}

5.字节过滤流


import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestBufferedOutput {

	public static void main(String[] args) throws IOException {
		//有参构造需要一个字节输出节点流
		//先创建字节输出节点流
		FileOutputStream fos = new FileOutputStream("E:\\qianfengjava\\day31");
		
		//增强节点流
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		//过滤流的write方法,是先写入到缓冲区数组里!
		bos.write('A');
		bos.write('B');
		bos.write('C');
		bos.write('D');
		
		bos.flush();//刷新缓冲区(将缓冲区的数据,一次性写入到文件中,并清空当前缓冲区)
		
		bos.write('E');
		bos.write('F');
		
		
//		bos.flush();
		bos.close();//级联的执行了flush();,释放资源的同时,将缓冲器的数据一次性写入到文件里

	}

}

6.File类

import java.io.File;
import java.io.IOException;

public class TestFiles {
	public static void main(String[] args) throws IOException, InterruptedException {
		File file = new File("E:\\test\\work.txt");
//		System.out.println(file.canExecute());//所有可以打开的文件或文件夹,都是可执行的
//		System.out.println(file.canWrite());//能不能修改文件
//		System.out.println(file.canRead());//能不能执行文件
//		
//		System.out.println(file.createNewFile());//新建一个文件,如果不存在的话
//		
//		System.out.println(file.delete());//如果文件存在则删除,返回true
		
//		Thread.sleep(2000);
//		file.deleteOnExit();//JVM终止时,执行删除文件
		
		System.out.println(file.exists());//路径文件或目录是否存在
		
		System.out.println(file.getAbsolutePath());//绝对
		System.out.println(file.getPath());//相对
		System.out.println(file.getName());//文件名 名字.后缀
		System.out.println(file.getFreeSpace()/1024/1024/1024);//获取硬盘的空闲空间,单位G
		System.out.println(file.getTotalSpace()/1024/1024/1024);//获取硬盘总空间  单位G
		System.out.println(file.getParent());//指定文件的上一级目录
		System.out.println(file.isDirectory());//判断是否为文件夹
		System.out.println(file.isFile());//判断是否为文件
		System.out.println(file.isHidden());//判断文件是否为隐藏
		System.out.println((System.currentTimeMillis()-file.lastModified())/1000/60);//获取文件最后一次修改时间
		System.out.println(file.length());//文件内容的字节长度
		System.out.println(file.canWrite());
		
		file.mkdirs();
	}

}
import java.io.File;
import java.io.FileFilter;

public class TestListFiles {

	public static void main(String[] args) {
		File file = new File("E:\\qianfengjava");
		String[] fileNames = file.list();//获取文件夹中的所有文件(包含文件夹)的名字 String类型
		for(String fname : fileNames) {//遍历
			System.out.println(fname);
		}
		
		File[] files = file.listFiles(new MyFilter());//获取文件夹中的所有文件(包含文件夹)的对象  File类型
		for(File f : files) {
			System.out.println(f.getName());
		}
//		for(File f : files) {
//			if(f.isFile()) {//判断是否是一个文件
//				if(f.getName().endsWith(".doc")) {//判断结尾是否是.doc
//					System.out.println(f.getName());
//				}
//			}
//			System.out.println(f.getName()+":"+f.isFile());
//		}
	}

}
class MyFilter implements FileFilter{//过滤器,筛选出以.doc结尾的文件

	@Override
	public boolean accept(File pathname) {//true就保存,false就过滤
		// TODO Auto-generated method stub
		if(pathname.isFile()) {//先判断是不是一个文件
			if(pathname.getName().endsWith(".doc")) {//再判断是不是以.doc结尾
				return true;//保存
			}
		}
		return false;//过滤
	}
	
}
import java.io.File;
import java.io.FileFilter;


public class TestShowAllFiles {
	static int count = 0;

	public static void main(String[] args) {
		//1.遍历E盘下,所有是.class为结尾的文件!
		
		File file = new File("E:\\");
		showall(file);
		System.out.println("一共"+count+"个文件");

	}
	
	public static void showall(File dir) {
		File[] files = dir.listFiles(new FileFilter() {//这是一个匿名内部类

			@Override
			public boolean accept(File f) {
				if(f.isDirectory()) {//判断是否是文件夹 是的话保存到files数组
					return true;
				}
				if(f.isFile()) {//判断是否是文件
					if(f.getName().endsWith(".class")) {//判断是否是以.class结尾
						return true;
					}
				}
				return false;
			}
		});
		
		//循环遍历输出
		if(files != null) {//先判断数组不是空再进行遍历,否则会空指针异常
			for(File f : files) {
				if(f.isFile()) {//如果是文件   打印
					System.out.println(f.getName());
					count++;//每输出一个加1,计数.class结尾文件的数量
				}else {
					showall(f);//如果是文件夹  递归调用,再次过滤符合要求的内容
				}
			}
		}
	}

}

7.字符流

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestBuffered {

	public static void main(String[] args) throws IOException {
		FileWriter fw = new FileWriter("Files\\buf.txt");
//		BufferedWriter bw = new BufferedWriter(fw);//过滤流
//		bw.write("Hello");
//		bw.newLine();//根据平台提供的换行符
		
		//过滤流! 比BufferedWriter更为方便!提供了println()打印后换行的方法
		PrintWriter pw = new PrintWriter(fw);
		pw.write("Hello");
		pw.write("world");
		pw.write("SayGoodBye");
		
		pw.flush();
		
		//-----------字符输入过滤流
		FileReader fr = new FileReader("Files\\buf2.txt");
		BufferedReader br = new BufferedReader(fr);
		String str = br.readLine();//文件末尾返回的是null
		System.out.println(str);

	}

}

8.桥转换流

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class TestConvertStream {

	public static void main(String[] args) throws IOException {
		//1.字节输出流
		OutputStream os = new FileOutputStream("Files\\convert.txt");//这是一个字节输出流
		//编码  2.转换为字符输出流
		OutputStreamWriter osw = new OutputStreamWriter(os,"GBK");//指定输出的数据  编码格式
		osw.write("你好世界");
		osw.flush();
		
		//换行输出  3.包装字符过滤流
		PrintWriter pw = new PrintWriter(osw);
//		PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream));
		pw.println("你好世界");
		pw.println("你好java");
		pw.println("你好web");
		pw.flush();
		
		
		
		//----------------
		//字节输出流
		InputStream is = new FileInputStream("Files\\convert.txt");
		//解码    2.转换为字符输入流
		InputStreamReader isr = new InputStreamReader(is,"GBK");
		
		char[] chars = new char[4];
		isr.read(chars);
		
		for(int i=0;i<chars.length;i++) {
			System.out.print(chars[i]);
		}
		
		//3.包装祖父过滤流
		BufferedReader br = new BufferedReader(isr);
		while(true) {
			String s = br.readLine();
			if(s==null) {
				
			}
		}

	}

}

9.字符编码

import java.io.UnsupportedEncodingException;

public class TestEncodiong {

	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "你好世界123abc";//文本内容!
		//编码     文本--》二进制
		byte[] bs = str.getBytes("GBK");//获得字符串的二进制表现形式
		for (int i = 0; i < bs.length; i++) {
			System.out.println(bs[i]);
		}
		//解码     二进制---》文本
		String str2 = new String(bs,"BIG5");
		System.out.println(str2);
		
		byte[] bs2 = str2.getBytes("BIG5");
		String str3 = new String(bs2,"GBK");
		System.out.println(str3);
		
		String s1 = "你好陶喆abc123";
		//编码   字符集是一致的
		byte[] b = s1.getBytes("UTF-8");
		//解码   字符集是一致的
		String s2 = new String(b,"UTF-8");
		System.out.println(s2);
				

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值