IO流(字节流、字符流)

IO流

IO流的划分

1.按照流的流向不同:输入流,输出流

2.按照流中的数据单位不同:字节流,字符流(纯文本文件使用字符流,其他文件使用字节流)

3.按照流的角色不同:节点流,处理流(流直接作用于文件上是节点流(4个(FileInputStream、FileOutputStream、FileReader、FileWrite)),除此之外是处理流)

牢记
1.只要是实现数据的传输,无论数据源和目的地是什么,传递的中间站必须经过内存。

​ 2.凡是从外界(键盘输入、文件、网络等)到内存都是输入流;从内存到外界都是输出流。

​ 3.对流进行编程,记住三要素:数据源、目的地、交通工具(流框架-----用什么流)

在这里插入图片描述

字节流

字节输出流(OutputStream、FileOutputStream、标准异常处理方式)

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Demo02 {
	public static void main(String[] args) throws IOException {
		OutputStream os = new FileOutputStream("os.txt");
		os.write(97);
		os.write("97".getBytes());
		os.write("\r\n".getBytes());
		os.write("HelloWorldJava".getBytes());
		os.write("\r\n".getBytes());
		os.write("HelloWorldJava".getBytes(), 10, 4);
		os.close();
	}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;

public class Demo03 {
	public static void main(String[] args) {
		LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>();
		lhm.put("poem", "静夜思");
		lhm.put("author", "李白");
		lhm.put("content", "床前明月光,疑是地上霜,举头望明月,低头思故乡");
		//创建输出流
		//FileOutputStream fos = null;
		/*//标准IO异常处理格式(必须牢记!!!)
		try {
			fos = new FileOutputStream("Poem.txt");
			//写诗名
			fos.write(lhm.get("poem").getBytes());
			fos.write("\r\n".getBytes());
			fos.write(lhm.get("author").getBytes());
			fos.write("\r\n".getBytes());
			String[] strs = lhm.get("content").split(",");
			for (String s : strs) {
				fos.write(s.getBytes());
				fos.write("\r\n".getBytes());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/

		/*JDK1.7之后新增加的简化异常处理方式
		try(需要关闭的资源对象代码){
		}
		*/
		try (FileOutputStream fos = new FileOutputStream("Poem.txt")) {
			//写诗名
			fos.write(lhm.get("poem").getBytes());
			fos.write("\r\n".getBytes());
			fos.write(lhm.get("author").getBytes());
			fos.write("\r\n".getBytes());
			String[] strs = lhm.get("content").split(",");
			for (String s : strs) {
				fos.write(s.getBytes());
				fos.write("\r\n".getBytes());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("over");
	}
}

字节输入流(InputStream 、FileInputStream)

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo04 {
	public static void main(String[] args) throws IOException {
		/*InputStream is = new FileInputStream("os.txt");
		//每次读取一个字节
		int b = is.read();
		while ((b = is.read()) != -1) {
			System.out.print((char) b);
		}
		is.close();
		*/
   FileInputStream fis = new FileInputStream("src\\com\\sxt\\outputstream\\Demo03.java");
		//每次读取一个字节数组	
		byte[] bys = new byte[1024];
		/*返回的是读取的长度
		int len = fis.read(bys);*/
		int len = 0;
		while ((len = fis.read(bys)) != -1) {
			System.out.print(new String(bys, 0, len));
		}
		fis.close();
	}
}

IO流实现文件拷贝

数据源:Poem.txt

目的地:C:\\Users\\Administrator\\Desktop\\poemCopy.txt

交通工具:文件——内存(输入流)

​ 内存——文件(输出流)

一次性读取一个字节拷贝文件
//一次性读取一个字节拷贝文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo05 {
	public static void main(String[] args) {
		copyFile("poem.txt", "C:\\Users\\Administrator\\Desktop\\poemCopy.txt");
	}

	/**
	 * 功能:一次性读取一个字节拷贝文件
	 * 
	 * @param String srcFileName 源文件名称
	 * @param String desFileName 目标文件名称
	 */
	public static void copyFile(String srcFileName, String desFileName) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(srcFileName);
			fos = new FileOutputStream(desFileName);
			int b = 0;
			while ((b = fis.read()) != -1) {
				fos.write(b);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}
}
一次性读取一个字节数组拷贝文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo06 {
	public static void main(String[] args) {
		copyFile("poem.txt", "C:\\Users\\Administrator\\Desktop\\poemCopy2.txt");
	}

	/**
	 * 功能:一次性读取一个字节数组拷贝文件
	 * 
	 * @param String srcFileName 源文件名称
	 * @param String desFileName 目标文件名称
	 */
	public static void copyFile(String srcFileName, String desFileName) {
		try (FileInputStream fis = new FileInputStream(srcFileName);
				FileOutputStream fos = new FileOutputStream(desFileName)) {
			byte[] bys = new byte[1024];
			int len = 0;
			while ((len = fis.read(bys)) != -1) {
				fos.write(bys, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

高效缓冲字节流(BufferedOutputStream、BufferedInputStream)

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

public class Demo07 {
	public static void main(String[] args) {
		copyMovie("E:\\JAVA课件\\JaveSE\\day18\\02_视频\\10.高效缓冲字节流拷贝文件.mp4", "src\\haha.mp4");
	}

	public static void copyMovie(String srcFileName, String desFileName) {
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFileName));
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFileName))) {
			byte[] by = new byte[1024];
			int len = 0;
			while ((len = bis.read(by)) != -1) {
				bos.write(by, 0, len);
				bos.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

编码与解码

1.处理字符情况

2.处理字符串情况

3.处理文本情况

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class Demo01 {
	public static void main(String[] args) throws UnsupportedEncodingException {
		//1.处理字符情况
		char ch = 'a';
		//编码
		System.out.println((int) ch);

		//解码
		System.out.println((char) 97);

		//2.处理字符串情况
		String s = "中国Hello";
		//编码
		//byte[] bys = s.getBytes();//[-42, -48, -71, -6, 72, 101, 108, 108, 111]
		byte[] bys = s.getBytes("UTF-8");//[-28, -72, -83, -27, -101, -67, 72, 101, 108, 108, 111]
		System.out.println(Arrays.toString(bys));
		//解码
		String str = new String(bys, "UTF-8");
		System.out.println(str);
		//3.处理文本情况(利用字符流)
	}
}

字符流

字符输出流(Writer)

Writer append(char c) 添加指定字符

Writer append(CharSequence csq) 添加指定字符序列

Writer append(CharSequence csq, int start, int end) 添加指定字符序列的一部分

abstract void close() 关闭此流,但要先刷新它

abstract void flush() 刷新该流

void write(char[] cbuf) 写入字符数组

abstract void write(char[] cbuf, int off, int len) 写入字符数组的一部分

void write(int c) 写入单个字符

void write(String str) 写入字符串

void write(String str, int off, int len) 写入字符串的一部分

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class Demo02 {
	public static void main(String[] args) throws Exception {
		Writer w = new OutputStreamWriter(new FileOutputStream("src\\w.txt"), "utf-8");
		w.write("HelloWorld");
		w.append("good");
		w.append("早上");
		w.append('好');
		w.write(new char[] { 'c', 'h', 'i', 'n', 'a' });
		w.write("中国");
		w.flush();
		w.close();
	}
}

字符输入流(Reader)

int read() 读取单个字符

int read(char[] cbuf) 读取字符数组

abstract int read(char[] cbuf, int off, int len)

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class Demo03 {
	public static void main(String[] args) throws Exception {
		Reader r = new InputStreamReader(new FileInputStream("src\\w.txt"), "utf-8");
		/*//1.读取单个字符
		int ch = 0;
		while ((ch = r.read()) != -1) {
			System.out.print((char) ch);
		}
		r.close();*/
		//2.读取字符数组
		char[] chs = new char[100];
		int len = 0;
		while ((len = r.read(chs)) != -1) {
			System.out.println(new String(chs, 0, len));
		}
		r.close();
	}
}
转换流拷贝文件(InputStreamReader、OutputStreamWriter)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Demo04 {
	public static void main(String[] args) throws IOException {
		InputStreamReader isr = new InputStreamReader(new FileInputStream(
				"F:\\eclipse\\eclipe-work\\java0928_Map\\src\\com\\sxt\\map\\Demo02.java"));
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"));
		char[] chs = new char[1024];
		int len = 0;
		while ((len = isr.read(chs)) != -1) {
			osw.write(chs, 0, len);
			osw.flush();
		}
		isr.close();
		osw.close();
	}
}
文件字符输入输出流(FileWriter、FileReader)
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Demo05 {
	public static void main(String[] args) throws Exception {
		// write();
		read();
	}

	public static void read() throws IOException {
		FileReader fr = new FileReader("poem.txt");
		int len = 0;
		char[] chs = new char[1024];
		while ((len = fr.read(chs)) != -1) {
			System.out.print(new String(chs, 0, len));
		}
		fr.close();
	}

	public static void write() throws IOException {
		FileWriter fw = new FileWriter("src\\fw.txt");
		fw.write("中国你好");
		fw.write(new char[] { 'c', 'h', 'i', 'n', 'a' });
		fw.flush();
		fw.close();
	}
}

高效缓冲字符流

BufferedWrite特有方法:支持写入换行方法 newline()
BufferedReader特有方法:支持读取一行 readline()

//BufferedWrite支持写入换行方法 	newline()
//BufferedReader支持读取一行  	readline()
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Demo06 {
	public static void main(String[] args) {
		//write();
		reader();
	}

	public static void reader() {
		try (BufferedReader br = new BufferedReader(new FileReader("osw.txt"))) {
			//读取一行
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void write() {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter("bw.txt"));
			bw.write("两只小蜜蜂呀");
			bw.newLine();//换行,所有系统都支持,不需要\r,\n,\r\n
			bw.write("飞在花丛中呀");
			bw.newLine();
			bw.append("飞呀");
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bw != null) {
					bw.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}

快速关闭io流的方法

public static void closeStream(Closeable... streamlist) {
		for (Closeable stream : streamlist) {
			if (stream != null) {
				try {
					stream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值