系列文章目录
文章目录
- 系列文章目录
- 一、学习总结
- 二、部分代码
一、学习总结
- IO流概览
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-11MLpicr-1690733294478)(src/main/resources/img.png)]
- IO流操作的步骤:
1.创建输入 或者 输出的文件对象
2.创建输入流 输出流
3.具体的读写操作
4.关闭流
3.注意点
1.关闭流
2.写文件有一个参数控制是覆盖还是追加 FileWriter(file,true) --true参数控制
3.字符流操作只能处理文本文件;字节流操作处理非文本文件 和 文本的复制操作
- 缓冲流 转换流 对象流
二、部分代码
package com.zy.learnio;import org.junit.Test;
import java.io.*;public class LearnIoTest {@Testpublic void testFileRead() throws IOException {/*** 1. 创建读取/写入的File类对象* 2. 创建输入流 输出流* 3. 具体操作:读取文件内容:方式1:按单个字符读取; 方式2. 按照字符数组读取* 4. 关流*/FileReader fr = null;try {File file = new File("hello.txt");fr = new FileReader(file);int data;// 方式1:单个字符读取
// while ((data = fr.read()) != -1) {
// System.out.println((char) data);
// }// 方式2: 按照字符数组读取char[] buff = new char[5];int len = fr.read(buff);while (len != -1) {for (int i = 0; i < len; i++) {System.out.println((char) buff[i]);}len = fr.read(buff);}} catch (Exception e) {e.printStackTrace();} finally {if (fr != null) {fr.close();}}}@Testpublic void testFileWrite() throws IOException {String s = "hello world test";File file = new File("hWrite.txt");FileWriter fw = null;try {fw = new FileWriter(file);// 方式1: 按照单个字符写
// for (int i = 0; i < s.length(); i++) {
// fw.write(s.charAt(i));
// }// 方式2:按照字符数组写/ 直接写入字符串char[] cBuff = new char[5];char[] chars = s.toCharArray();fw.write(s);} catch (IOException e) {e.printStackTrace();} finally {if (fw != null) {fw.close();}}}@Testpublic void testFileInputStream() {File file = new File("hello.txt");FileInputStream fIn = null;try {fIn = new FileInputStream(file);int read = fIn.read();while (read != -1) {System.out.println((char) read);read = fIn.read();}} catch (IOException e) {e.printStackTrace();} finally {if (fIn != null) {try {fIn.close();} catch (IOException e) {e.printStackTrace();}}}}@Testpublic void testFileOutputStream() {File file = new File("hOutputStream.txt");FileOutputStream fo = null;try {fo = new FileOutputStream(file);byte[] bytes = "test 123".getBytes();fo.write(bytes);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fo != null) {try {fo.close();} catch (IOException e) {e.printStackTrace();}}}}@Testpublic void testFileInputStreamAndFileOutputStream() {File srcFile = new File("img.png");File dstFile = new File("outTest.jpg");FileInputStream fi = null;FileOutputStream fo = null;try {fi = new FileInputStream(srcFile);fo = new FileOutputStream(dstFile);byte[] bytes = new byte[1024];int len;while ((len = fi.read(bytes)) != -1) {fo.write(bytes, 0, len);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fi != null) {try {fi.close();} catch (IOException e) {e.printStackTrace();}}if (fo != null) {try {fo.close();} catch (IOException e) {e.printStackTrace();}}}}
}