Java 第十一章.IO流
1.File的使用
1.1概念
- java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关
- File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。
如果需要访问文件内容本身,则需要使用输入/输出流。 - 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对 象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录
- File对象可以作为参数传递给流的构造器
构造器
public File(String pathname) 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
绝对路径:是一个固定的路径,从盘符开始
相对路径:是相对于某个位置开始
public File(String parent,String child)以parent为父路径,child为子路径创建File对象。
public File(File parent,String child)根据一个父File对象和子文件路径创建File对象
@Test
/*
1.创建File类的实例
File(String filePath)
File(String parentPath,String childPath)
File(File parentFile,String childPath)
2.
相对路径:相对于当前模块
绝对路径:D:\IDEA LiTi\IO流\hello.txt
*/
public void test1() {
//构造器一
File file1 = new File("hello.txt");//相对于当前模块
File file2 = new File("D:\\IDEA LiTi\\IO流\\hello.txt");
System.out.println(file1);
System.out.println(file2);
//构造器二
File file3 = new File("D:\\\\IDEA LiTi","IO流");
System.out.println(file3);
//构造器三
File file4 = new File(file3,"hello.txt");
System.out.println(file4);
}
1.2常用操作
File类的获取功能
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。 public long lastModified() :获取最后一次的修改时间,毫秒值
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
File类的重命名功能
public boolean renameTo(File dest):把文件重命名为指定的文件路径
File类的判断功能
public boolean isDirectory():判断是否是文件目录
public boolean isFile() :判断是否是文件
public boolean exists() :判断是否存在
public boolean canRead() :判断是否可读
public boolean canWrite() :判断是否可写
public boolean isHidden() :判断是否隐藏
File类的创建功能
public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
注意事项:如果你创建文件或者文件目录没有写盘符路径,那么,默认在项目路径下。
File类的删除功能
public boolean delete():删除文件或者文件夹
删除注意事项:
Java中的删除不走回收站。
要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
@Test
public void test2() throws IOException {
File file1= new File("hello.txt");
System.out.println(file1.isDirectory());
System.out.println(file1.isFile());
System.out.println(file1.exists());
System.out.println(file1.canRead());
System.out.println(file1.canWrite());
System.out.println(file1.isHidden());
System.out.println("************");
File file2 = new File("hello1.txt");
System.out.println(file2.createNewFile());
System.out.println(file2.delete());
System.out.println("*************");
File file3 = new File("d:\\IDEA LiT\\li");
System.out.println(file3.mkdirs());
System.out.println(file3.delete());
}
例题
import java.io.File;
import java.io.IOException;
public class LiTiTest {
public static void main(String[] args) throws IOException {
/*
1. 利用File构造器,new 一个文件目录file
1)在其中创建多个文件和目录
2)编写方法,实现删除file中指定文件的操作
*/
File file1 = new File("d:\\\\IDEA LiTi","lhk");
if (file1.mkdir()){
System.out.println("创建成功!");
}else{
System.out.println("创建失败!");
}
File file2 = new File("d:\\\\IDEA LiTi\\lhk","lhk524");
file2.mkdir();
File file3 = new File(file1,"hello.txt");
file3.createNewFile();
File file4 = new File(file1,"hello7.txt");
file4.createNewFile();
if(file4.delete()){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
}
}
2.IO流原理及流的分类
2.1IO概述与分类
概述
- I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
- Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。
- java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据
分类
- 按操作数据单位不同:字节流(8bit),字符流(16bit)
- 按数据流的流向不同:输入流,输出流
- 按流的角色的不同:节点流,处理流
2.2IO流的体系结构
3.节点流(文件流)
3.1FileReader读入数据的基本操作
步骤
//将IO流下的hello.txt文件内容读入到程序中,并输出到控制台
//1.read():返回读入的一个字符。如果达到文件末尾,返回-1
//2.异常的处理:为了保证流资源一定可以执行关闭操作,使用try- catch -finally
//3.读入的文件一定要存在
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前module
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符。如果达到文件末尾,返回-1
int data = fr.read();
while(data != -1){
System.out.print((char)data);
data = fr.read();
}
//4.流的关闭操作
fr.close();
举例
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLOutput;
public class demo01 {
public static void main(String[] args) {
File file = new File("hello.txt");//相较于当前工程(IDEA Test)
System.out.println(file.getAbsolutePath());
File file1 = new File("IO流\\hello.txt");
System.out.println(file.getAbsolutePath());
}
//将IO流下的hello.txt文件内容读入到程序中,并输出到控制台
//1.read():返回读入的一个字符。如果达到文件末尾,返回-1
//2.异常的处理:为了保证流资源一定可以执行关闭操作,使用try- catch -finally
//3.读入的文件一定要存在
@Test
public void testFileReader() {
FileReader fr = null;
try {
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前module
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符。如果达到文件末尾,返回-1
// int data = fr.read();
// while(data != -1){
// System.out.print((char)data);
// data = fr.read();
// }
//语法上的修改
int data;
while((data = fr.read()) != -1){
System.out.println((char)data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭操作
try {
if(fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.1FileReader中使用read(char[] cbuf)读入数据
@Test
public void testFileReader1() {
FileReader fr = null;
try {
//1.File类的实例化
File file = new File("hello.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cbuf);返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,就返回-1
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) {
// 方式一
// for (int i = 0; i < len; i++) {
// System.out.print(cbuf[i]);
// }
//方式二
String str = new String(cbuf,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null){
//4.资源的关闭
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.2FileWriter写出数据的操作
//从内存中写出数据到硬盘的文件里
//1.输出操作,对应的File可以不存在。并不会报异常
//2.对应的File如果不存在,就会创建相应的文件
// 对应的File如果存在
// 如果流使用的构造器是:FileWriter(file)/FileWriter(file,false),则会对源文件内容进行覆盖
// 如果流使用的构造器是:FileWriter(file,true),则会在源文件内容的后面写入
@Test
public void testFileWriter() {
FileWriter fw = null;
try {
//1.提供File类的对象,指明要写出单的文件
File file = new File("hello1.txt");
//2.提供FileWriter类的对象,由于数据的写出
fw = new FileWriter(file,true);
//3.写出的操作
fw.write("我有一个梦想!\n");
fw.write("我也有一个梦想!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null){
//关闭流资源
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.4使用FileRead和FileWriter实现文本文件的复制
@Test
public void testFileReaderFileWriter() {
FileReader fr = null;
FileWriter fw = null;
try {
//1.创建File类的对象
File file1 = new File("hello.txt");
File file2 = new File("hello2.txt");
//2.创建流的对象
fr = new FileReader(file1);
fw = new FileWriter(file2);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;//记录每次读入到cbuf数组中的字符的个数
while((len = fr.read(cbuf)) != -1){
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null || fw != null) {
//4.关闭流的资源
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.5字符流不能处理图片文件的测试
@Test
public void testFileReaderFileWriter1() {
FileReader fr = null;
FileWriter fw = null;
try {
//1.创建File类的对象
File file1 = new File("金智秀.jpg");
File file2 = new File("金智秀1.jpg");
//2.创建流的对象
fr = new FileReader(file1);
fw = new FileWriter(file2);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) {
fw.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null || fw != null) {
//4.关闭流的资源
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.6使用FileInputStream不能读取文本文件的测试
//结论
//1.对于文本文件(.txt .java .c .cpp),使用字符流
//2.对于非文本文件(.jpg .mp3 .mp4 .avi .ppt .doc),使用字节流处理
@Test
public void testFileInputStream() {
FileInputStream fis = null;
try {
//1.创建File类的对象
File file = new File("hello.txt");
//2.创建流的对象
fis = new FileInputStream(file);
//3.读数据
byte[] buffer = new byte[5];
int len;//记录每次读取的字节的个数
while ((len = fis.read(buffer)) != -1){
String str = new String(buffer,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null){
//4.关闭流资源
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.7使用FileInputStream和FileOutputStream读写非文本文件
//实现图片的复制
@Test
public void FileInputOutputStream() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//1.实例化File类
File file1 = new File("金智秀.jpg");
File file2 = new File("金智秀2.jpg");
//2.创建流的对象
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
//3.读写操作
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null || fos != null){
//4.关闭流资源
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.8使用FileInputStream和FileOutputStream复制文件的方法测试
//指定路径下文件的复制(视频,图片······)
public void copyTest(String srcPath, String destPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//1.实例化File类
File file1 = new File(srcPath);
File file2 = new File(destPath);
//2.创建流的对象
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
//3.读写操作
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null || fos != null) {
//4.关闭流资源
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void Test() {
long startTime = System.currentTimeMillis();
String srcPath ="E:\\黑马\\2022-3-08B站直播.wmv";
String destPath ="E:\\黑马\\复制.wmv";
copyTest(srcPath,destPath);
long endTime = System.currentTimeMillis();
System.out.println("复制所需要花费的时间" + (endTime - startTime));
}
//指定路径下文件的复制 文本文件可以(直接复制过去,没有在内存层面去读)
public void copyTest1(String srcPath, String destPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//1.实例化File类
File file1 = new File(srcPath);
File file2 = new File(destPath);
//2.创建流的对象
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
//3.读写操作
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null || fos != null) {
//4.关闭流资源
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void Test1() {
long startTime = System.currentTimeMillis();
String srcPath ="hello.txt";
String destPath ="hello3.txt";
copyTest1(srcPath,destPath);
long endTime = System.currentTimeMillis();
System.out.println("复制所需要花费的时间" + (endTime - startTime));
}
4.缓冲流(处理流的一种)
缓冲流:
bufferedInputStream
bufferedOutputStream
bufferedReader
bufferedWriter
作用:提高流的读取,写入的速度
4.1缓冲流(字节型)实现非文本文件的复制
@Test
public void test() {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("金智秀.jpg");
File destFile = new File("金智秀3.jpg");
//2.造流
//2.1早字节流
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.读写操作
byte[] buffered = new byte[10];
int len;
while((len = bis.read(buffered)) != -1){
bos.write(buffered,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis != null || bos != null){
//4.关闭流资源
//4.1要求:先关闭外层的流,在关闭内层的流
//4.2说明:关闭外层流的同时,内层流也会自动地进行关闭。关于内层流的关闭我们可以省略!
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.2缓冲流和节点流读写速度对比
public void copyFileBuffered(String srcPath,String destPath){
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.造流
//2.1早字节流
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.读写操作
byte[] buffered = new byte[5];
int len;
while((len = bis.read(buffered)) != -1){
bos.write(buffered,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis != null|| bos != null){
//4.关闭流资源
//4.1要求:先关闭外层的流,在关闭内层的流
//4.2说明:关闭外层流的同时,内层流也会自动地进行关闭。关于内层流的关闭我们可以省略!
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void test1(){
long startTime = System.currentTimeMillis();
String srcPath ="E:\\黑马\\2022-3-08B站直播.wmv";
String destPath ="E:\\黑马\\2022.wmv";
copyFileBuffered(srcPath,destPath);
long endTime = System.currentTimeMillis();
System.out.println("复制所需要花费的时间" + (endTime - startTime));
}
4.3缓冲流(字符流)实现文本文件的复制
@Test
public void copyFileReaderWriterBuffered() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
//1 2
br = new BufferedReader(new FileReader(new File("网址.txt")));
bw = new BufferedWriter(new FileWriter(new File("网址1.txt")));
//3
//方式一:
// char[] buffered = new char[10];
// int len;
// while((len = br.read(buffered)) != -1){
// bw.write(buffered,0,len);
// // bw.flush();
// }
//方式二:使用String
String data;
while((data = br.readLine()) != null){
//方法一
bw.write(data + "\n");//data中不包含换行符
//方法二
bw.write(data);
bw.newLine();//提供换行操作
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null){
//4
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null){
//4
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.转换流
1.转换流:属于字符流
InputStreamReader:将一个字节的输入流转换为字符的输入流
OutputStreamWriter:将一个字符的输出流转换为字节的输出流
2.作用:提供字节流与字符流之间的转换
3.编码:字节,字节数组 ----->字符串,字符数组
编码:字符串,字符数组 ----->字节,字节数组
4.字符集
5.1InputStreamReader的使用
@Test
public void Test() {
InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("网址.txt");
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
// 参数二指明了字符集,具体使用那个字符集,根据网址.txt使用的字符集一样
isr = new InputStreamReader(fis,"UTF-8" );
char[] cbuf = new char[10];
int len;
while ((len = isr.read(cbuf)) != -1) {
String str = new String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.2转换流实现文件的读入与写出
@Test
public void copyReaderWriter(){
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
File file1 = new File("网址.txt");
File file2 = new File("网址2.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
isr = new InputStreamReader(fis,"utf-8");
osw = new OutputStreamWriter(fos,"gbk");
char[] cbuf = new char[10];
int len;
while((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (osw != null){
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.3多种字符编码集的说明
6.标准输入,输出流
System.in和System.out分别代表了系统标准的输入和输出设备
默认输入设备是:键盘,输出设备是:显示器
System.in的类型是InputStream
System.out的类型是PrintStream,其是OutputStream的子类
FilterOutputStream 的子类
重定向:通过System类的setIn,setOut方法对默认设备进行改变。
public static void setIn(InputStream in)
public static void setOut(PrintStream out)
1.System.in: 标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出
2.System类的setIn(InputStream is)/ setOut(PrintStream ps)方式重新指定输入输出的流
3.练习:
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续
进行输入操作,直至当输入“e”或者“exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用System.in实现。System.in ---->转换流---->BufferedReader的readLine()
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class OtherTest {
//标准的输入,输出流
public static void main(String[] args) {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while (true) {
System.out.println("请输入字符串:");
String data = br.readLine();
if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
System.out.println("程序结束!");
break;
}
String upperCase = data.toUpperCase();
System.out.println(upperCase);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
7.打印流
实现将基本数据类型的数据格式转化为字符串输出
打印流:PrintStream和PrintWriter
提供了一系列重载的print()和println()方法,用于多种数据类型的输出
PrintStream和PrintWriter的输出不会抛出IOException异常
PrintStream和PrintWriter有自动flush功能
PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
System.out返回的是PrintStream的实例
@Test
public void test2(){
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("E:\\IO\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
ps = new PrintStream(fos, true);
if (ps != null) {// 把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i = 0; i <= 255; i++) { // 输出ASCII字符
System.out.print((char) i);
if (i % 50 == 0) { // 每50个数据一行
System.out.println(); // 换行
} }
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
} }
}
8.数据流
为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
DataInputStream 和 DataOutputStream
分别“套接”在 InputStream 和 OutputStream 子类的流上
DataInputStream中的方法
boolean readBoolean()
byte readByte()
char readChar()
float readFloat()
double readDouble()
short readShort()
long readLong()
int readInt()
String readUTF()
void readFully(byte[] b)
DataOutputStream中的方法
将上述的方法的read改为相应的write即可。
//数据流
@Test
public void test3() {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("李翰");
dos.flush();
dos.writeInt(18);
dos.flush();
dos.writeBoolean(true);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中
//读的顺序和写的时候顺序一样
@Test
public void test4() {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("data.txt"));
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name:" + name);
System.out.println("age:" + age);
System.out.println("isMale:" + isMale);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
9.对象流
说明
1. ObjectInputStream和OjbectOutputSteam
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
2. 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
3. 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
4. ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
步骤
使用对象流序列化对象
1.若某个类实现了 Serializable 接口,该类的对象就是可序列化的:
1.1创建一个 ObjectOutputStream
1.2调用 ObjectOutputStream 对象的 writeObject(对象) 方法输出可序列化对象
1.3注意写出一次,操作flush()一次
2.反序列化
2.1创建一个 ObjectInputStream
2.2调用 readObject() 方法读取流中的对象
3.强调:如果某个类的属性不是基本数据类型或 String 类型,而是另一个引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的Field 的类也不能序列化
了解
对象的序列化
1.对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
2.序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原
3.序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是JavaEE 平台的基础
4.如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。
否则,会抛出NotSerializableException异常
Serializable
Externalizable
对象的序列化
1.凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
1.1private static final long serialVersionUID;
1.2serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
1.3如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议,显式声明。
2. 简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。(InvalidCastException)
举例
//序列化
@Test
public void test1(){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("你好.dat"));
oos.writeObject(new String("我爱你?"));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//反序列化
@Test
public void ObjectInputStreamTest(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("你好.dat"));
Object obj = ois.readObject();
String str = (String)obj;
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
自定义类实现序列化,反序列化
import java.io.Serializable;
/*
Person需要满足以下要求,才可以序列化
1.需要实现接口:Serializable
2.当前类提供一个全局变量:serialVersionUID
3.除以上条件外,还需要保证内部所有属性都是可序列化的。(默认情况下,基本数据类型是可序列化的)
4.ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
*/
public class Person implements Serializable {
public static final long serialVersionUID = 8527412985412l;
private String name;
private int 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;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//序列化
@Test
public void test1(){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("你好.dat"));
oos.writeObject(new String("我爱你?"));
oos.flush();
oos.writeObject(new Person("李航",29));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//反序列化
@Test
public void ObjectInputStreamTest(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("你好.dat"));
Object obj = ois.readObject();
String str = (String)obj;
System.out.println(str);
Object obj1 = ois.readObject();
Person p = (Person)obj1;
System.out.println(p);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
10.随机存取文件流
RandomAccessFile 类
RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。
RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读、写文件
支持只访问文件的部分内容
可以向已存在的文件后追加内容
RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。RandomAccessFile 类对象可以自由移动记录指针:
long getFilePointer():获取文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到 pos 位置(不调用seek(pos)默认从头开始覆盖,即指针定位到0)
RandomAccessFile 类
构造器
public RandomAccessFile(File file, String mode)
public RandomAccessFile(String name, String mode)
创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:
r: 以只读方式打开
rw:打开以便读取和写入
rwd:打开以便读取和写入;同步文件内容的更新
rws:打开以便读取和写入;同步文件内容和元数据的更新
如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。
RandomAccessFile实现数据的读写操作
//RandomAccessFile的使用
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
@Test
public void test() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("金智秀1.jpg"),"r");
raf2 = new RandomAccessFile(new File("金智秀4.jpg"),"rw");
byte[] buffer = new byte[10];
int len;
while((len = raf1.read(buffer)) != -1){
raf2.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf1 != null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (raf2 != null){
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
RandomAccessFile实现数据的覆盖操作
@Test
public void test2() {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("hello.txt", "rw");
raf.seek(3);
raf.write("xyz".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}