第六章 文件&IO流


6.1、File类

描述:该类是文件和目录路径名的抽象表示

构造方法:

方法 描述
public File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的File实例
public File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的File实例
public File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的File实例

成员方法:

创建功能:

方法 描述
public boolean createNewFile() 当具有该名称的文件不存在时,创建一个由该抽象路径名命名的新空文件
public boolean mkdir() 创建由此抽象路径名命名的单级目录
public boolean mkdirs() 创建由此抽象路径名命名的多级目录

判断功能:

方法 描述
public boolean isDirectory() 测试此抽象路径名表示的File是否为目录
public boolean isFile() 测试此抽象路径名表示的File是否为文件
public boolean exists() 测试此抽象路径名表示的File是否存在

获取功能:

方法 描述
public String getAbsolutePath() 返回此抽象路径名的绝对路径名字符串
public String getPath() 将此抽象路径名转换为路径名字符串
public String getName() 返回由此抽象路径名表示的文件或目录的名称
public String[] list() 返回此抽象路径名表示的目录中的文件和目录的名称字符串数组
public File[] listFiles() 返回此抽象路径名表示的目录中的文件和目录的File对象数组

删除功能:

方法 描述
public boolean delete() 删除由此抽象路径名表示的文件或目录

6.2、IO流

概述:IO流就是用来处理设备间数据传输问题的。常见的应用:文件复制、文件上传、文件下载、文件的读取、文件的写出等等

分类:

按照数据流向来分:
	输入流:读数据
	输出流:写数据
	
按照数据类型来分:
	字节流
		字节输入流
		字节输出流
	字符流
		字符输入流
		字符输出流

注意:

  1. 如果操作的是纯文本文件,优先使用字符流
  2. 如果操作的是图片、视频、音频、应用等二进制文件,优先使用字节流
  3. 如果不确定文件类型,优先使用字节流,字节流是万能的流

6.2.1、字节流

体系:

image-20200717234833960

6.2.1.1、字节流写数据的三种方式

方法 描述
public void write(int b) 写入一个字节
public void write(byte[] b) 写入一个字节数组
public void write(byte[] b, int off, int len) 写入一个字节数组的一部分

6.2.1.2、字节流读数据的三种方式

方法 描述
public abstract int read() 读入一个字节
public int read(byte[] b) 读入一个字节数组
public int read(byte[] b, int off, int len) 读入一个字节数组的一部分

6.2.1.3、字节流复制文件的四种方式

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

public class Main {
	public static void main(String[] args) throws IOException {
		method1();
		method2();
		method3();
		method4();
	}

	// 基本字节流一次读写一个字节
	public static void method1() throws IOException {
		FileInputStream fis = new FileInputStream("sFolder\\demo.txt");
		FileOutputStream fos = new FileOutputStream("dFolder\\demo.txt");

		int by;
		while ((by = fis.read()) != -1) {
			fos.write(by);
		}

		fos.close();
		fis.close();
	}

	// 基本字节流一次读写一个字节数组
	public static void method2() throws IOException {
		FileInputStream fis = new FileInputStream("sFolder\\demo.txt");
		FileOutputStream fos = new FileOutputStream("dFolder\\demo.txt");

		byte[] bys = new byte[1024];
		int len;
		while ((len = fis.read(bys)) != -1) {
			fos.write(bys, 0, len);
		}

		fos.close();
		fis.close();
	}

	// 字节缓冲流一次读写一个字节
	public static void method3() throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("sFolder\\demo.txt"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("dFolder\\demo.txt"));

		int by;
		while ((by = bis.read()) != -1) {
			bos.write(by);
		}

		bos.close();
		bis.close();
	}

	// 字节缓冲流一次读写一个字节数组
	public static void method4() throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("sFolder\\demo.txt"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("dFolder\\demo.txt"));

		byte[] bys = new byte[1024];
		int len;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}

		bos.close();
		bis.close();
	}
}

6.2.2、字符流

体系:

image-20200718002001318

6.2.2.1、字符流写数据的五种方式

方法 描述
public void write(int c) 写入一个字符
public void write(char[] cbuf) 写入一个字符数组
public void write(char[] cbuf, int off, int len) 写入一个字符数组的一部分
public void write(String str) 写入一个字符串
public void write(String str, int off, int len) 写入一个字符串的一部分

6.2.2.2、字符流读数据的四种方式

方法 描述
public int read() 读入一个字符
public int read(char[] cbuf) 读入一个字符数组
public int read(char[] cbuf, int offset, int length) 读入一个字符数组的一部分
public String readLine() 读入一个字符串

6.2.2.3、字符流复制文本的七种方式

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
	public static void main(String[] args) throws IOException {
		method1();
		method2();
		method3();
		method4();
		method5();
		method6();
		method7();
	}

	// 基本字符流一次读写一个字符
	public static void method1() throws IOException {
		InputStreamReader isr = new InputStreamReader(new FileInputStream("sFolder\\demo.txt"));
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("dFolder\\demo.txt"));

		int ch;
		while ((ch = isr.read()) != -1) {
			osw.write(ch);
		}

		osw.close();
		isr.close();
	}

	// 基本字符流一次读写一个字符数组
	public static void method2() throws IOException {
		InputStreamReader isr = new InputStreamReader(new FileInputStream("sFolder\\demo.txt"));
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("dFolder\\demo.txt"));

		char[] chs = new char[1024];
		int len;
		while ((len = isr.read(chs)) != -1) {
			osw.write(chs, 0, len);
		}

		osw.close();
		isr.close();
	}

	// 文件字符流一次读写一个字符
	public static void method3() throws IOException {
		FileReader fr = new FileReader("sFolder\\demo.txt");
		FileWriter fw = new FileWriter("dFolder\\demo.txt");

		int ch;
		while ((ch = fr.read()) != -1) {
			fw.write(ch);
		}

		fw.close();
		fr.close();
	}

	// 文件字符流一次读写一个字符数组
	public static void method4() throws IOException {
		FileReader fr = new FileReader("sFolder\\demo.txt");
		FileWriter fw = new FileWriter("dFolder\\demo.txt");

		char[] chs = new char[1024];
		int len;
		while ((len = fr.read(chs)) != -1) {
			fw.write(chs, 0, len);
		}

		fw.close();
		fr.close();
	}

	// 字符缓冲流一次读写一个字符
	public static void method5() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("sFolder\\demo.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("dFolder\\demo.txt"));

		int ch;
		while ((ch = br.read()) != -1) {
			bw.write(ch);
		}

		bw.close();
		br.close();
	}

	// 字符缓冲流一次读写一个字符数组
	public static void method6() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("sFolder\\demo.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("dFolder\\demo.txt"));

		char[] chs = new char[1024];
		int len;
		while ((len = br.read(chs)) != -1) {
			bw.write(chs, 0, len);
		}

		bw.close();
		br.close();
	}

	// 字符缓冲流特有功能复制文本文件
	public static void method7() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("sFolder\\demo.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("dFolder\\demo.txt"));

		String line;
		while ((line = br.readLine()) != null) {
			bw.write(line);
			bw.newLine();
		}

		bw.close();
		br.close();
	}
}

6.3、文件夹复制

6.3.1、复制单级文件夹

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

public class Main {
	public static void main(String[] args) throws IOException {
		File srcFolder = new File("D:\\sFolder");
		File destFolder = new File("D:\\dFolder");
		copyFolder(srcFolder, destFolder);
	}

	/**
	 * 复制单级文件夹
	 * 
	 * @param srcFolder  源文件夹
	 * @param destFolder 目的文件夹
	 * @throws IOException
	 */
	private static void copyFolder(File srcFolder, File destFolder) throws IOException {
		// 判断路径是否存在
		if (!destFolder.exists()) {
			destFolder.mkdirs();
		}
		// 获取目的文件列表
		File[] listFiles = srcFolder.listFiles();
		// 遍历目的文件列表
		for (File file : listFiles) {
			copyFile(file, new File(destFolder, file.getName()));
		}
	}

	/**
	 * 复制文件
	 * 
	 * @param srcFile  源文件
	 * @param destFile 目的文件
	 * @throws IOException
	 */
	private static void copyFile(File srcFile, File destFile) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
		byte[] bys = new byte[1024];
		int len;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}
		bos.close();
		bis.close();
	}
}

6.3.2、复制多级文件夹

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

public class Main {
	public static void main(String[] args) throws IOException {
		File srcFolder = new File("D:\\sFolder");
		File destFolder = new File("D:\\dFolder");
		copyFolder(srcFolder, destFolder);
	}

	/**
	 * 复制多级文件夹
	 * 
	 * @param srcFolder  源文件夹
	 * @param destFolder 目的文件夹
	 * @throws IOException
	 */
	private static void copyFolder(File srcFolder, File destFolder) throws IOException {
		// 判断路径是否存在
		if (!destFolder.exists()) {
			destFolder.mkdirs();
		}
		// 获取目的文件列表
		File[] listFiles = srcFolder.listFiles();
		// 遍历目的文件列表
		for (File file : listFiles) {
			if (file.isDirectory()) {
				copyFolder(file, new File(destFolder, file.getName()));
			} else {
				copyFile(file, new File(destFolder, file.getName()));
			}
		}
	}

	/**
	 * 复制文件
	 * 
	 * @param srcFile  源文件
	 * @param destFile 目的文件
	 * @throws IOException
	 */
	private static void copyFile(File srcFile, File destFile) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
		byte[] bys = new byte[1024];
		int len;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}
		bos.close();
		bis.close();
	}
}

6.3.3、捕获异常新特性

6.3.3.1、JDK7以前做法

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
	public static void main(String[] args) {
		method();
	}

	private static void method() {
		FileReader fr = null;
		FileWriter fw = null;
		try {
			fr = new FileReader("fr.txt");
			fw = new FileWriter("fw.txt");
			char[] chs = new char[1024];
			int len;
			while ((len = fr.read()) != -1) {
				fw.write(chs, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fr != null) {
				try {
					fr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

6.3.3.2、JDK7版本改进

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
	public static void main(String[] args) {
		method();
	}

	private static void method() {
		try (FileReader fr = new FileReader("fr.txt"); 
			 FileWriter fw = new FileWriter("fw.txt");) {
			char[] chs = new char[1024];
			int len;
			while ((len = fr.read()) != -1) {
				fw.write(chs, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

6.4、IO特殊流

6.4.1、标准输入流

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

public class Main {
	public static void main(String[] args) throws IOException {
		InputStream is = System.in;

		int by;
		while ((by = is.read()) != -1) {
			System.out.print((char) by);
		}

		is.close();
	}
}

6.4.2、标准输出流

import java.io.IOException;
import java.io.PrintStream;

public class Main {
	public static void main(String[] args) throws IOException {
		PrintStream ps = System.out;

		ps.println("Hello,World");
		ps.write("Hello,World".getBytes());

		ps.close();
	}
}

6.4.3、字节打印流

import java.io.IOException;
import java.io.PrintStream;

public class Main {
	public static void main(String[] args) throws IOException {
		PrintStream ps = new PrintStream("ps.txt");

		ps.println(97);
		ps.write(97);

		ps.close();
	}
}

6.4.4、字符打印流

import java.io.IOException;
import java.io.PrintWriter;

public class Main {
	public static void main(String[] args) throws IOException {
		PrintWriter pw = new PrintWriter("pw.txt");

		pw.println("hello");
		pw.write("Hello");

		pw.close();
	}
}

6.4.5、对象序列化流

注意:需要实现Serializable接口,同时需要给出serialVersionUID

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Student implements Serializable {
	private static final long serialVersionUID = 5923003911550370832L;
	private String name;
	private Integer age;

	public Student() {
		super();
	}

	public Student(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

public class Main {
	public static void main(String[] args) throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));

		Student s = new Student("曹晨磊", 30);
		oos.writeObject(s);

		oos.close();
	}
}

6.4.6、对象反序列化流

注意:成员变量加transient关键字修饰,该关键字标记的成员变量不参与序列化过程

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

class Student implements Serializable {
	private static final long serialVersionUID = 5923003911550370832L;
	private String name;
	private Integer age;

	public Student() {
		super();
	}

	public Student(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

public class Main {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));

		Object obj = ois.readObject();
		Student s = (Student) obj;
		System.out.println(s);

		ois.close();
	}
}

6.5、Properties集合

import java.util.Properties;
import java.util.Set;

public class Main {
	public static void main(String[] args) {
		Properties prop = new Properties();

		// 存储元素
		prop.put("student1", "林青霞");
		prop.put("student2", "张曼玉");

		// 普通遍历
		Set<Object> keySet = prop.keySet();
		for (Object key : keySet) {
			Object value = prop.get(key);
			System.out.println(key + "," + value);
		}

		// 特有方法
		prop.setProperty("student3", "赵云");
		prop.setProperty("student4", "张飞");

		// 特有遍历
		Set<String> names = prop.stringPropertyNames();
		for (String key : names) {
			String value = prop.getProperty(key);
			System.out.println(key + "," + value);
		}
	}
}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class Main {
	public static void main(String[] args) throws IOException {
		// 把集合中的数据保存到文件
		myStore();
		// 把文件中的数据加载到集合
		myLoad();
	}

	private static void myStore() throws IOException {
		Properties prop = new Properties();
		prop.setProperty("student1", "林青霞");
		prop.setProperty("student2", "张曼玉");
		FileWriter fw = new FileWriter("fw.txt");
		prop.store(fw, null);
		fw.close();
	}

	private static void myLoad() throws IOException {
		Properties prop = new Properties();
		FileReader fr = new FileReader("fw.txt");
		prop.load(fr);
		fr.close();
		System.out.println(prop);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38490457/article/details/107494793