流的总结

File类

File的作用

通过路径字符串可以表示操作系统中的文件或文件夹

File类的构造方法

File(String pathname) 通过路径名创建一个File对象,这个File对象可以表示文件也表示文件夹

File(String parent, String child) 通过父类路径和子类路径创建File对象

File(File parent, String child) 通过父路径File对象和子路径创建File对象

// 文件路径名
String pathname = "D:\\aaa.txt";
File file1 = new File(pathname);

// 文件路径名
String pathname2 = "D:\\aaa\\bbb.txt";
File file2 = new File(pathname2);

// 通过父路径和子路径字符串
String parent = "d:\\aaa";
String child = "bbb.txt";
File file3 = new File(parent, child);

// 通过父级File对象和子路径字符串
File parentDir = new File("d:\\aaa");
String child = "bbb.txt";
File file4 = new File(parentDir, child);

注意:

1.一个File对象代表硬盘中实际存在的一个文件或者目录。

2.无论该路径下是否存在文件或者目录,都不影响File对象的创建。

File类的创建功能

boolean createNewFile() 创建新文件, 如果创建成功返回true

boolean mkdir() 创建一个文件夹, 如果创建成功返回true (make direcotry)

boolean mkdirs() 创建多个文件夹, 如果创建成功返回true (make direcotrys)

public class Demo02 {
    public static void main(String[] args) throws IOException {
        test3();
    }

	// boolean mkdirs() (推荐使用)创建多级文件夹, 如果创建成功返回true
	public static void test3() {
    	File file = new File("C:/MyFileTest/666/777/888");
    	boolean b = file.mkdirs();
    	System.out.println("是否创建成功" + b);
	}

	// boolean mkdir() 创建一个文件夹, 如果创建成功返回true
	public static void test2() {
    	// File file = new File("C:\\MyFileTest\\ccc");
    	// File file = new File("C:\\MyFileTest\\CCC");
   	 	File file = new File("C:/MyFileTest/ddd");
    	boolean b = file.mkdir();
   		System.out.println("是否创建成功" + b);
	}

	// boolean createNewFile() 创建新文件,如果创建成功返回true
	public static void test1() throws IOException {
    	File file = new File("C:\\MyFileTest\\123.txt");

    	boolean b = file.createNewFile();
   	 	System.out.println("是否创建成功" + b);
	}
    
}

输出结果:
是否创建成功: true
是否创建成功: true
是否创建成功: true
File类的删除功能

boolean delete() 删除文件或文件夹,删除成功返回true

File in = new File("C:\\MyFileTest\\ddd\\aaa");
System.out.println("删除里面内容: " + in.delete());

File file = new File("C:\\MyFileTest\\ddd");
boolean b = file.delete();
System.out.println("删除文件夹: " + b);

输出结果:
删除里面内容: true
删除文件夹: true

注意:
1.如果文件加里面有内容,需要先删除文件夹里面的内容,再删除空文件夹

2.删除就没有了.不会再回收站里

File类的获取功能

String getAbsolutePath() 返回绝对路径

String getPath() 返回创建File对象时的路径

String getName() 返回路径的名称

long length() 返回文件的长度。

public class Demo05 {
	public static void main(String[] args) {
        // String getAbsolutePath() 返回绝对路径
        File file = new File("C:\\MyFileTest\\aaa");
        System.out.println("绝对路径:" + file.getAbsolutePath());
    	// String getPath() 返回创建File对象时的路径
    	System.out.println("路径:" + file.getPath());
	
    	// String getName() 返回路径的名称
    	System.out.println("路径的名称:" + file.getName());

    	// long length() 返回文件的长度。
    	System.out.println("文件的长度:" + file.length());
	
    	System.out.println("------------");
    	File file2 = new File("day09demo/abc/1.txt");
   	 	System.out.println("绝对路径:" + file2.getAbsolutePath());
    	System.out.println("路径:" + file2.getPath());
    	System.out.println("路径的名称:" + file2.getName());
    	System.out.println("文件的长度:" + file2.length());
	}
}
输出结果:
绝对路径: C:\MyFileTest\aaa
路径: C:\MyFileTest\aaa
路径的名称: aaa
文件的长度: 0
------------
绝对路径: C:\Users\13666\IdeaProjects\JavaUp117\day09demo\abc\1.txt
路径: day09demo\abc\1.txt
路径的名称: 1.txt
文件的长度: 35

注意:

length(),表示文件的长度。但是File对象表示目录,则返回值未指定。

File判断功能

boolean isDirectory() 判断是否是文件夹,如果是返回true

boolean isFile() 判断是否是文件,如果是返回true

boolean exists() 判断是否存在,如果存在返回true

public class FileIs {
	public static void main(String[] args) {
	File f = new File("d:\\aaa\\bbb.java");
	File f2 = new File("d:\\aaa");
	    
	// boolean exists() 判断是否存在,如果存在返回true
	System.out.println("d:\\aaa\\bbb.java 是否存在:"+f.exists());
	System.out.println("d:\\aaa 是否存在:"+f2.exists());
    
	// boolean isFile() 判断是否是文件,如果是返回true
    // boolean isDirectory() 判断是否是文件夹,如果是返回true
	System.out.println("d:\\aaa 文件?:"+f2.isFile());
	System.out.println("d:\\aaa 目录?:"+f2.isDirectory());
	}
}

输出结果:
d:\aaa\bbb.java 是否存在:true
d:\aaa 是否存在:true
d:\aaa 文件?:false
d:\aaa 目录?:true

File目录的遍历

String[] list() 列出文件夹里面的所有内容,返回文件名数组

File[] listFiles() (常用) 列出文件夹里面的所有内容,返回File对象数组

public class Demo07 {
    public static void main(String[] args) {
        // test1();
        // test2();
        test3();
    }
    
	// 文件不能调用list功能
	public static void test3() {
	    File file = new File("C:\\MyFileTest\\123.txt");
	    File[] files = file.listFiles();
	    System.out.println(files); // null
	}
    
	// File[] listFiles() (常用)列出文件夹里面的所有内容,返回File对象数组
	public static void test2() {
	    File file = new File("C:\\MyFileTest\\aaa");
	
	    // 列出文件夹里面的所有内容,返回File对象数组
	    File[] files = file.listFiles();
	
	    for (File f : files) {
	        System.out.println(f);
	    }
	}
	
	// String[] list() 列出文件夹里面的所有内容,返回文件名数组
	public static void test1() {
	    File file = new File("C:\\MyFileTest\\aaa");
	
	    // 列出文件夹里面的所有内容,返回文件名数组
	    String[] list = file.list();
	    // 遍历数组
	    for (String name : list) {
	        System.out.println(name);
	    }
	}

}

注意:

调用listFiles方法的File对象,表示的必须是实际存在的目录,否则返回null,无法进行遍历。

IO流

IO流的分类:
按照流向:
输入流 :把数据从其他设备上读取到内存中的流。
输出流 :把数据从内存中写出到其他设备上的流。

按操作的类型:
字节流: 操作的单位是字节
字符流: 操作的单位是字符,方便我们操作字符

IO流的顶级父类:
字节流 字符流
输入流 字节输入流InputStream 字符输入流Reader
输出流 字节输出流OutputStream 字符输出流Writer

字节流

一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样
如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传
输的始终为二进制数据。

FileOutputStream类

OutputStream:字节输出流的父类

构造方法

FileOutputStream(String name) 创建一个文件字节输出流,流中的数据会流入指定的文件中

FileOutputStream(File file) 创建一个文件字节输出流,流中的数据会流入指定的文件中

写出字节数据

void write(int b) 将一个字节写入流中

public class Demo13 {
    public static void main(String[] args) throws IOException, InterruptedException {
        // FileOutputStream(String name) 创建一个文件字节输出流,流中的数据会流入指定的文件中
        // FileOutputStream fos = new FileOutputStream("day09demo/abc/2.txt");

    // FileOutputStream(File file)
    File file = new File("day09demo/abc/3.txt");
    FileOutputStream fos2 = new FileOutputStream(file);

    // void write(int b) 将一个字节写入流中
    // 我们要写字节byte,参数是int,不怕.
    fos2.write(97);

    // IO流使用完需要关闭
    fos2.close();

    // 模拟程序一直运行
    // Thread.sleep(10000);

	}
}

注意:

1.虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。

2.流操作完毕后,必须释放系统资源,调用close方法,千万记得。

写出字节数组

void write(byte[] b) 将字节数组中的数据写入流中

public class FOSWrite {
	public static void main(String[] args) throws IOException {
	// 使用文件名称创建流对象
	FileOutputStream fos = new FileOutputStream("fos.txt");
	
	// 字符串转换为字节数组
	byte[] b = "你好".getBytes();
	
	// 写出字节数组数据
	fos.write(b);
	
	// 关闭资源
	fos.close();
	}	
}

输出结果:
你好

void write(byte[] b, int off, int len) 将字节数组中的部分数据写入流中

public class FOSWrite {
	public static void main(String[] args) throws IOException {
	// 使用文件名称创建流对象
	FileOutputStream fos = new FileOutputStream("fos.txt");
	
	// 字符串转换为字节数组	
	byte[] b = "abcde".getBytes();
	
	// 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
	fos.write(b,2,2);
	
	// 关闭资源
	fos.close();
	}
}

输出结果:
cd
数据追加续写

FileOutputStream(File file, boolean append)

FileOutputStream(String name, boolean append)

append设置为true时,就不会删掉以前的,在之前的基础上追加写入数据

public class FOSWrite {
	public static void main(String[] args) throws IOException {
	// 使用文件名称创建流对象
	FileOutputStream fos = new FileOutputStream("fos.txt"true);
	
	// 字符串转换为字节数组
	byte[] b = "abcde".getBytes();
	
	// 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
	fos.write(b);
	
	// 关闭资源
	fos.close();
	}
}

文件操作前:cd
文件操作后:cdabcde
写出换行
Windows系统里,换行符号是 \r\n 。把

以指定是否追加续写了,代码使用演示:

public class FOSWrite {
	public static void main(String[] args) throws IOException {
	// 使用文件名称创建流对象
		FileOutputStream fos = new FileOutputStream("fos.txt");
		
		// 定义字节数组
		byte[] words = {97,98,99,100,101};
		
		// 遍历数组
		for (int i = 0; i < words.length; i++) {
			
			// 写出一个字节
			fos.write(words[i]);
			
			// 写出一个换行, 换行符号转成数组写出
			fos.write("\r\n".getBytes());
		}
		// 关闭资源
		fos.close();	
	}
}

输出结果:
a
b
c
d
e	

FileInputStream类

InputStream:字节输入流的父类

构造方法

FileInputStream(File file) : 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系

统中的 File对象 file命名。

FileInputStream(String name) : 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件

系统中的路径名 name命名。

当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有该文件,会抛出 FileNotFoundException 。

构造举例,代码如下:

public class FileInputStreamConstructor throws IOException{
	public static void main(String[] args) {
		// 使用File对象创建流对象
		File file = new File("a.txt");
		FileInputStream fos = new FileInputStream(file);
    	    	
		// 使用文件名称创建流对象
		FileInputStream fos = new FileInputStream("b.txt");
	}
}
读取字节数据

读取字节: read 方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回 -1 ,代码使用
演示:

public class FISRead {
	public static void main(String[] args) throws IOException{
	// 使用文件名称创建流对象
		FileInputStream fis = new FileInputStream("read.txt");
		
		// 定义变量,保存数据
		int b ;
		
		//	 循环读取
		while ((b = fis.read())!=-1) {
			System.out.println((char)b);
		}
		// 关闭资源
		fis.close();
	}
}

输出结果:
a
b
c
d
e
读取字节数组

read(byte[] b) ,每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取
到末尾时,返回 -1 ,代码使用演示:

public class FISRead {
	public static void main(String[] args) throws IOException{
	// 使用文件名称创建流对象.
		FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
        
		// 定义变量,作为有效个数
		int len ;
            
		// 定义字节数组,作为装字节数据的容器
		byte[] b = new byte[2];
        
		// 循环读取
		while (( len= fis.read(b))!=-1) {
			// 每次读取后,把数组的有效字节部分,变成字符串打印
			System.out.println(new String(b,0,len));// len 每次读取的有效字节个数
		}
	// 关闭资源
		fis.close();
	}
}

输出结果:
ab
cd
e

注意:使用数组读取,每次读取多个字节,减少了系统间的IO操作次数,从而提高了读写的效率,建议开发中使用。

字节流练习:图片复制
public class Copy {
	public static void main(String[] args) throws IOException {
		// 1.创建流对象
		// 1.1 指定数据源
		FileInputStream fis = new FileInputStream("D:\\test.jpg");
        
		// 1.2 指定目的地
		FileOutputStream fos = new FileOutputStream("test_copy.jpg");
        
		// 2.读写数据
		// 2.1 定义数组
		byte[] b = new byte[1024];
        
		// 2.2 定义长度
		int len;
        
		// 2.3 循环读取
		while ((len = fis.read(b))!=-1) {
		// 2.4 写出数据
			fos.write(b, 0 , len);
		}
		// 3.关闭资源
		fos.close();
		fis.close();
	}
}

注意:流的关闭原则:先开后关,后开先关。

字符流

当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一
个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。

FileReader类

java.io.FileReader 类是读取字符文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。

构造方法

FileReader(File file) : 创建一个新的 FileReader ,给定要读取的File对象。

FileReader(String fileName) : 创建一个新的 FileReader ,给定要读取的文件的名称。

当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream 。

构造举例,代码如下:

public class FileReaderConstructor throws IOException{
	public static void main(String[] args) {
		// 使用File对象创建流对象
		File file = new File("a.txt");
		FileReader fr = new FileReader(file);
        
		// 使用文件名称创建流对象
		FileReader fr = new FileReader("b.txt");
	}
}
读取字符数据

read 方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回 -1 ,循环读

取,代码使用演示:

public class FRRead {
	public static void main(String[] args) throws IOException {
		// 使用文件名称创建流对象
		FileReader fr = new FileReader("read.txt");
        
		// 定义变量,保存数据
		int b ;
            
		// 循环读取
		while ((b = fr.read())!=-1) {
			System.out.println((char)b);
		}
        
		// 关闭资源
		fr.close();
	}
}

输出结果:
你
好
读取字符数组

read(char[] cbuf) ,每次读取b的长度个字符到数组中,返回读取到的有效字符个数,

读取到末尾时,返回 -1 ,代码使用演示:

	public class FISRead {
	public static void main(String[] args) throws IOException {
	// 使用文件名称创建流对象
		FileReader fr = new FileReader("read.txt");
        
		// 定义变量,保存有效字符个数
		int len ;
            
		// 定义字符数组,作为装字符数据的容器
		char[] cbuf = new char[2];
        
		// 循环读取
		while ((len = fr.read(cbuf))!=-1) {
			System.out.println(new String(cbuf,0,len));
		}
		// 关闭资源
		fr.close();
	}
}
输出结果:
你好
中国

FileWriter类

java.io.FileWriter 类是写出字符到文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。

构造方法

FileWriter(File file) : 创建一个新的 FileWriter,给定要读取的File对象。

FileWriter(String fileName) : 创建一个新的 FileWriter,给定要读取的文件的名称。

当你创建一个流对象时,必须传入一个文件路径,类似于FileOutputStream。

构造举例,代码如下:

public class FileWriterConstructor {
	public static void main(String[] args) throws IOException {
		// 使用File对象创建流对象
		File file = new File("a.txt");
		FileWriter fw = new FileWriter(file);
		
		// 使用文件名称创建流对象
		FileWriter fw = new FileWriter("b.txt");
	}
}
基本写出数据

write(int b) 方法,每次可以写出一个字符数据,代码使用演示:

public class FWWrite {
	public static void main(String[] args) throws IOException {
		// 使用文件名称创建流对象
		FileWriter fw = new FileWriter("fw.txt");
        
		// 写出数据
		fw.write(97); // 写出第1个字符
		fw.write('b'); // 写出第2个字符
		fw.write('C'); // 写出第3个字符
		fw.write(30000); // 写出第4个字符,中文编码表中30000对应一个汉字。
		/*
		【注意】关闭资源时,与FileOutputStream不同。
		如果不关闭,数据只是保存到缓冲区,并未保存到文件。
		*/
		// fw.close();
	}
}

输出结果:
abC田

注意:

1.虽然参数为int类型四个字节,但是只会保留一个字符的信息写出。

2.未调用close方法,数据只是保存到了缓冲区,并未写出到文件中。

关闭和刷新

因为内置缓冲区的原因,如果不关闭输出流,无法写出字符到文件中。但是关闭的流对象,是无法继续写出数据的。

如果我们既想写出数据,又想继续使用流,就需要 flush 方法了。

flush :刷新缓冲区,流对象可以继续使用。

close :关闭流,释放系统资源。关闭前会刷新缓冲区。

代码使用演示:

public class FWWrite {
    public static void main(String[] args) throws IOException {
    	// 使用文件名称创建流对象
    	FileWriter fw = new FileWriter("fw.txt");
    	
    	// 写出数据,通过flush
    	fw.write('刷'); // 写出第1个字符nj. 
    	fw.flush();
    	fw.write('新'); // 继续写出第2个字符,写出成功
    	fw.flush();
    	
    	// 写出数据,通过close
    	fw.write('关'); // 写出第1个字符
    	fw.close();
    	fw.write('闭'); // 继续写出第2个字符,【报错】java.io.IOException: Stream closed
		fw.close();
    }
}
续写和换行

操作类似于FileOutputStream。

public class FWWrite {
	public static void main(String[] args) throws IOException {
		// 使用文件名称创建流对象,可以续写数据
		FileWriter fw = new FileWriter("fw.txt"true);
        
		// 写出字符串
		fw.write("你");
        
		// 写出换行
		fw.write("\r\n");
        
		// 写出字符串
		fw.write("好");
        
		// 关闭资源
		fw.close();
	}
}

输出结果:
你
好

注意:字符流,只能操作文本文件,不能操作图片,视频等非文本文件。当我们单纯读或者写文本文件时 使用字符流 其他情况使用字节流

缓冲流

缓冲流,也叫高效流,是对4个基本的 FileXxx 流的增强,所以也是4个流,按照数据类型分类:

字节缓冲流: BufferedInputStream , BufferedOutputStream

字符缓冲流: BufferedReader , BufferedWriter

缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次

数,从而提高读写的效率。

字节缓冲流

构造方法

public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流。

public BufferedOutputStream(OutputStream out) : 创建一个新的缓冲输出流。

构造举例,代码如下:

// 创建字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));

// 创建字节缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));	
读取字节数据
public class BufferedDemo {
	public static void main(String[] args) throws FileNotFoundException {
		// 记录开始时间
		long start = System.currentTimeMillis();
		// 创建流对象
		try (BufferedInputStream bis = new BufferedInputStream(new
			FileInputStream("jdk8.exe"));
			BufferedOutputStream bos = new BufferedOutputStream(new
			FileOutputStream("copy.exe"));
		){
			// 读写数据
			int b;
			while ((b = bis.read()) != -1) {
				bos.write(b);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 记录结束时间
		long end = System.currentTimeMillis();
		System.out.println("缓冲流复制时间:"+(end - start)+" 毫秒");
	}
}

缓冲流复制时间:8016 毫秒
读取字节数组
public class BufferedDemo {
	public static void main(String[] args) throws FileNotFoundException {
		// 记录开始时间
		long start = System.currentTimeMillis();
		// 创建流对象
		try (BufferedInputStream bis = new BufferedInputStream(new
			FileInputStream("jdk8.exe"));
			BufferedOutputStream bos = new BufferedOutputStream(new
			FileOutputStream("copy.exe"));
		){
			// 读写数据
			int len;
			byte[] bytes = new byte[8*1024];
			while ((len = bis.read(bytes)) != -1) {
			bos.write(bytes, 0 , len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 记录结束时间
		long end = System.currentTimeMillis();
		System.out.println("缓冲流使用数组复制时间:"+(end - start)+" 毫秒");
	}
}
缓冲流使用数组复制时间:666 毫秒

字符缓冲流

构造方法

public BufferedReader(Reader in) :创建一个 新的缓冲输入流。

public BufferedWriter(Writer out) : 创建一个新的缓冲输出流。

构造举例,代码如下:

// 创建字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("br.txt"));

// 创建字符缓冲输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
特有方法

字符缓冲流的基本方法与普通字符流调用方式一致,不再阐述,我们来看它们具备的特有方法。

BufferedReader: public String readLine() : 读一行文字。

BufferedWriter: public void newLine() : 写一行行分隔符,由系统属性定义符号。

readLine 方法演示,代码如下:

public class BufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		// 创建流对象
		BufferedReader br = new BufferedReader(new FileReader("in.txt"));
        
		// 定义字符串,保存读取的一行文字
		String line = null;
        
		// 循环读取,读取到最后返回null
		while ((line = br.readLine())!=null) {
			System.out.print(line);
			System.out.println("------");
		}
		// 释放资源
		br.close();
	}
}

newLine 方法演示,代码如下:

public class BufferedWriterDemo throws IOException {
	public static void main(String[] args) throws IOException {
	// 创建流对象
		BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
		// 写出数据
		bw.write("你");
		// 写出换行
		bw.newLine();
		bw.write("好");
		bw.newLine();
		bw.write("中国");
		bw.newLine();
		// 释放资源
		bw.close();
	}
}

输出效果:
你
好
中国

转换流

InputStreamReader类

转换流 java.io.InputStreamReader ,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定

的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法

InputStreamReader(InputStream in) : 创建一个使用默认字符集的字符流。

InputStreamReader(InputStream in, String charsetName) : 创建一个指定字符集的字符流。

构造举例,代码如下:

InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));

InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");
指定编码读取
public class ReaderDemo2 {
	public static void main(String[] args) throws IOException {
		// 定义文件路径,文件为gbk编码
		String FileName = "E:\\file_gbk.txt";
		// 创建流对象,默认UTF8编码
		InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
		// 创建流对象,指定GBK编码
		InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) ,"GBK");
		// 定义变量,保存字符
		int read;
		// 使用默认编码字符流读取,乱码
		while ((read = isr.read()) != -1) {
			System.out.print((char)read); // ��Һ�
		}
		isr.close();
		// 使用指定编码字符流读取,正常解析
		while ((read = isr2.read()) != -1) {
			System.out.print((char)read);// 大家好
		}
		isr2.close();
	}
}

OutputStreamWriter类

转换流 java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符

编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法

OutputStreamWriter(OutputStream in) : 创建一个使用默认字符集的字符流。

OutputStreamWriter(OutputStream in, String charsetName) : 创建一个指定字符集的字符流。

构造举例,代码如下:

OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));

OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");
指定编码写出
public class OutputDemo {
	public static void main(String[] args) throws IOException {
		// 定义文件路径
		String FileName = "E:\\out.txt";
        
		// 创建流对象,默认UTF8编码
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
        
		// 写出数据
		osw.write("你好"); // 保存为6个字节
		osw.close();
        
		// 定义文件路径
		String FileName2 = "E:\\out2.txt";
        
		// 创建流对象,指定GBK编码
		OutputStreamWriter osw2 = new OutputStreamWriter(newFileOutputStream(FileName2),"GBK");
        
		// 写出数据
		osw2.write("你好");// 保存为4个字节
		osw2.close();
	}
}

序列化

ObjectOutputStream类

java.io.ObjectOutputStream 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。

构造方法

public ObjectOutputStream(OutputStream out) : 创建一个指定OutputStream的

ObjectOutputStream。

构造举例,代码如下:

FileOutputStream fileOut = new FileOutputStream("employee.txt");

ObjectOutputStream out = new ObjectOutputStream(fileOut);
序列化操作
  1. 一个对象要想序列化,必须满足两个条件:

该类必须实现 java.io.Serializable 接口, Serializable 是一个标记接口,不实现此接口的类将不会使任

何状态序列化或反序列化,会抛出 NotSerializableException 。

该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用

transient 关键字修饰。

public class Employee implements java.io.Seri	alizable {
	public String name;
	public String address;
	public transient int age; // transient瞬态修饰成员,不会被序列化
	public void addressCheck() {
		System.out.println("Address check : " + name + " -- " + address);
	}
}

2.写出对象方法

public final void writeObject (Object obj) : 将指定的对象写出。

public class SerializeDemo{
	public static void main(String [] args) {
		Employee e = new Employee();
		e.name = "zhangsan";
		e.address = "beiqinglu";
		e.age = 20;
		try {
			// 创建序列化流对象
			ObjectOutputStream out = new ObjectOutputStream(newFileOutputStream("employee.txt"));
			
			// 写出对象
			out.writeObject(e);
			
			// 释放资源
			out.close();
			fileOut.close();
			System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。
		} catch(IOException i) {
			i.printStackTrace();
		}
	}
}

输出结果:
Serialized data is saved

ObjectInputStream类

ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。

构造方法

public ObjectInputStream(InputStream in) : 创建一个指定InputStream的ObjectInputStream。

反序列化操作1

如果能找到一个对象的class文件,我们可以进行反序列化操作,调用 ObjectInputStream 读取对象的方法:

public final Object readObject () : 读取一个对象。

public class DeserializeDemo {
	public static void main(String [] args) {
		Employee e = null;
		try {
			// 创建反序列化流
			FileInputStream fileIn = new FileInputStream("employee.txt");
            ObjectInputStream in = new ObjectInputStream(fileIn);
			// 读取一个对象
			e = (Employee) in.readObject();
			// 释放资源
			in.close();
			fileIn.close();
		}catch(IOException i) {
			// 捕获其他异常
			i.printStackTrace();
			return;
		}catch(ClassNotFoundException c) {
				// 捕获类找不到异常
			System.out.println("Employee class not found");
			c.printStackTrace();
			return;
		}
		// 无异常,直接打印输出
		System.out.println("Name: " + e.name); // zhangsan
		System.out.println("Address: " + e.address); // beiqinglu
		System.out.println("age: " + e.age); // 0
	}
}

注意:对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出一个ClassNotFoundException 异常。

反序列化操作2

另外,当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么反序列化操作

也会失败,抛出一个 InvalidClassException 异常。发生这个异常的原因如下:

该类的序列版本号与从流中读取的类描述符的版本号不匹配

该类包含未知数据类型

该类没有可访问的无参数构造方法

Serializable 接口给需要序列化的类,提供了一个序列版本号。 serialVersionUID 该版本号的目的在于验证序

列化的对象和对应类是否版本匹配。

public class Employee implements java.io.Serializable {
	// 加入序列版本号
	private static final long serialVersionUID = 1L;
	public String name;
	public String address;
	// 添加新的属性 ,重新编译, 可以反序列化,该属性赋为默认值.
	public int eid;
    
	public void addressCheck() {
		System.out.println("Address check : " + name + " -- " + address);
	}
}

打印流

平时我们在控制台打印输出,是调用 print 方法和 println 方法完成的,这两个方法都来自于

java.io.PrintStream 类,该类能够方便地打印各种数据类型的值,是一种便捷的输出方式。

PrintStream类

构造方法

public PrintStream(String fileName) : 使用指定的文件名创建一个新的打印流。

构造举例,代码如下:

PrintStream ps = new PrintStream("ps.txt")

System.out 就是 PrintStream 类型的,只不过它的流向是系统规定的,打印在控制台上。不过,既然是流对象,

我们就可以玩一个"小把戏",将数据输出到指定文本文件中。

public class PrintDemo {
	public static void main(String[] args) throws IOException {
		// 调用系统的打印流,控制台直接输出97
		System.out.println(97);
        
		// 创建打印流,指定文件的名称
		PrintStream ps = new PrintStream("ps.txt");
        
		// 设置系统的打印流流向,输出到ps.txt
		System.setOut(ps);
        
		// 调用系统的打印流,ps.txt中输出97
		System.out.println(97);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值