Java Io 流 笔记<文件流><对象流><缓冲流>

一、什么是Io 流?

与文件或文件内容相关的称为IO流,在JDK中java.io包下

流的应用:

操作硬盘中的文件,获取文件内容    文件流   

网络通讯,点对点的通讯     数据流 

流就是二进制,指的是内容

二、Io 流常用方法及常量

 createNewFile()             创建一个新的文件    

mkdir()               创建文件夹,只能创建单层目录    

mkdirs()             创建文件夹,创建多层目录    

exists()              判断文件是否存在,存在返回true,否则返回false    

delete()              删除文件或文件夹,文件不存在,返回false, 如果删除文件夹,只能删除空文件夹    

listFiles()           获取指定目录下的所有文件列表,返回文件数组    

getName()        获取文件名    

getPath()          获取文件路径    

getParent()       获取文件父路径    

length()             获取文件大小    

isFile()              判断是否是一个文件    

isDirectory()     判断是否是一个文件夹    

isHidden()        判断是否是一个隐藏文件    

常用常量        

File.separator          文件分隔符        

File.pathSeparator      路径分隔符

三、Io 流分类

字节流

字节输入流         InputStream(抽象类) 以字节的形式读取

字节输出流          OutputStream   以字节的形式写入

字符流

字符输入流          Reader     以字符的形式读取

字符输出流         Writer      以字符的形式写入

注:以上四个基类都是抽象类

四、文件流

文件的内容的读写

文件字节流

文件字节输入流     FileInputStream    以字节的形式读取文

文件字节输出流     FileOutputStream  以字节的形式写入文件

文件字符流

文件字符输入流     FileReader         以字符的形式读取文件

文件字符输出流     FileWriter         以字符的形式写入文件

文件随机流 RandomAccessFile              支持文件的读与写

1) 使用FileInputStream读取文件

public class FileInput{
	//文件路径
	private static final String FilePath = "D:\\xxx.txt";
	public static void main(String[] args) {
		//创建输入流对象
		InputStream in = null;
		try{
			in = new FileInputStream(FilePath);
			//字节数组
			byte[] data = new byte[1024*10];
			int length = 0;
			while((length = in.read(data))!=-1){
				System.out.println(new String(data,0,length));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("文件读取完成!");
		}
	} 
}

2)使用FileOutputStream写入文件

//文件路径
	private static final String FilePath = "D:\\h.txt";
	public static void main(String[] args) {
		//创建输出流对象
		OutputStream out = null;
		try{
			out = new FileOutputStream(FilePath);
			//写入字符串内容
			String content = "文件字节流输入!";
			//转换字节数组
			byte[] data = content.getBytes();
			out.write(data);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("文件输入完成!");
		}
	} 

3)使用FileWriter写入文件

public class FileW {
	//文件路径
		private static final String FilePath = "D:\\h.txt";
		public static void main(String[] args) {
			//创建输出流对象
			Writer writer = null;
			try{
				writer = new FileWriter(FilePath,true);
				//写入字符串内容
				String content = "文件字符流输入!";
				//转换字符数组
				char[] data = content.toCharArray();
				writer.write(data);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println("文件输入完成!");
			}
		} 
}

4)使用 FileReader读取文件

public class FileR {
//文件路径
	private static final String FilePath = "D:\\xxx.txt";
	public static void main(String[] args) {
		//创建输入流对象
		Reader reader = null;
		try{
			reader = new FileReader(FilePath);
			//字符数组
			char[] data = new char[50];
			int length = 0;
			while((length = reader.read(data))!=-1){
				System.out.println(new String(data));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("文件读取完成!");
		}
	} 
}

5)使用文件字节流复制文件

 public static void copyFile(File srcFile,File destFile){
        //如果原文件不存在
        if(!srcFile.exists()){
            return;
        }
        //如果目标文件存在
        if(destFile.exists()){
            destFile.delete();
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] data = new byte[1024*1024];
            int length = 0;
            //边读边写
            while((length = in.read(data))!= -1){
                out.write(data,0,length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

6)复制文件夹

public static void copyFolder(File srcFile,File destFile){
        if(!srcFile.exists()){
            return;
        }
        if(srcFile.isDirectory()){//如果是文件夹
            if(!destFile.exists()){
               destFile.mkdir();
            }
            File[] files = srcFile.listFiles();
            for(File f : files){
                //目标文件父文件夹,子文件
                File def = new File(destFile,f.getName());
                copyFolder(f,def);
            }
        }else{//如果是文件
            copyFile(srcFile,destFile);//复制文件
        }
    }

复制文件夹 File重载 源码

五、对象流

对象流可以把对象存入或读取到硬盘中,是java创建对象的方式之一

ObjectOutputStream 对象输出流 序列化 把对象从内存写入到硬盘

ObjectInputStream 对象输入流 反序列化 把对象从硬盘读取到内存

写入的对象必须实现 java.io.Serializable接口,此接口是一个空接口

常见实现了Serializable接口的类:

1、八大基本数据类型包装类

2、String

3、Date

4、集合:ArrayList、LinkedList、HashSet、treeSet、HashSet

1)自定义类User实现Serializable 接口

public class User implements Serializable {
    private String name;

    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2) ObjectInputputStream 对象输入流  反序列化

public class ObjectInput{
    public static void main(String[] args) {
		File file = new File("D:\\xxx\\h.txt");
		InputStream in = null;
		ObjectInputStream oi = null;
		try{
			in = new FileInputStream(file);
			oi = new ObjectInputStream(in);
			User user = (User)oi.readObject();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				oi.close();
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

3)ObjectOutputStream 对象输出流 序列化

public class ObjectOutput {
	public static void main(String[] args) {
		User user = new User("xx",21);
		File file = new File("D:\\xxx\\h.txt");
		OutputStream out = null;
		ObjectOutputStream oo = null;
		try{
			out = new FileOutputStream(file);
			oo = new ObjectOutputStream(out);
			oo.writeObject(user);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				oo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

六、数据流

数据流一般用于网络通讯传输内容,针对数据类型传输的流,数据流只有字节流没有字符流 DataOutputStream 数据输出流 写入数据

DataInputStream 数据输入流 读取数据

七、缓冲流

提高读写效率,减少IO读写,把内容先装进缓冲区 缓冲区满了之后再同步到文件中
BufferedInputStream 缓冲字节输入流 用来读取
BufferedOutputStream 缓冲字节输出流 用来写入
BufferedReader 缓冲字符输入流 用来读取
BufferedWriter 缓冲字符输出流 用来写入
注:以上缓冲区默认大小 字节缓冲8kb,字符缓冲8192个字符 

1)BufferedInputStream 缓冲字节输入流

public class BufferedInputStreamTest {
    public static void main(String[] args) {
        File file = new File("E:\\buffer.txt");
        InputStream in = null;
        BufferedInputStream bufferIn = null;
        try {
            in = new FileInputStream(file);
            bufferIn = new BufferedInputStream(in);
            byte[] data = new byte[8*1024];
            int length = 0;
            while((length = bufferIn.read(data))!=-1){
                System.out.println(new String(data,0,1024));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferIn.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2)BufferedOutputStream 缓冲字节输出流

public class BufferedOutputStreamTest {
    public static void main(String[] args) {
        File file = new File("E:\\buffer.txt");
        OutputStream out = null;
        BufferedOutputStream bufferOut = null;
        try {
            out = new FileOutputStream(file);
            bufferOut = new BufferedOutputStream(out);
            byte[] data = "我与春风皆过客,我携秋水揽星河".getBytes("UTF-8");
            bufferOut.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }   finally {
            try {
                bufferOut.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值