IO基础使用

IO1

1 File

File对象表示一个路径,可以是文件的路径也可以是文件夹的路径

这个路径可以是存在的也可以是不存在的

其构造方法包括

public File(String pathname)   通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
public File(String parent,String child)  根据父目录和子目录创建文件对象
public File(File parent ,String child)  根据父路径对应的文件对象和子路径名字字符串创建文件对象
 		  // 根据字符串表示的路径编程File对象
        // 为什么要将字符串变为File对象
        // 在java中 字符串仅仅是个字符串 但变成File对象对象后就可以使用里面的方法了
        String str = "IOStream-01-File\\AboutFile.txt";
        File file = new File(str);
        System.out.println(file);

        // 根据父目录和子目录创建文件对象
        String parent = "F:\\JavaCode\\IOStream";
        String child = "AboutFile.txt";
        // File.separator 自动获取当前系统的分隔符
        File file1 = new File(parent, child);
        // File file1 = new File(parent + File.separator + child);
        System.out.println(file1);

        // 3.把一个File表示的路径和String表示路径进行拼接
        File parent2 = new File("F:\\JavaCode\\IOStream");
        String child2 = "AboutFile.txt";
        File f4 = new File(parent2,child2);
        System.out.println(f4);

常用方法

public boolean isDirectory()        判断此路径名表示的File是否为文件夹
public boolean isFile()             判断此路径名表示的File是否为文件
public boolean exists()             判断此路径名表示的File是否存在
public long length()                返回文件的大小(字节数量)
    
public String getAbsolutePath()     返回文件的绝对路径
public String getPath()             返回定义文件时使用的路径
public String getName()             返回文件的名称,带后缀
public long lastModified()          返回文件的最后修改时间(时间毫秒值)
    
public boolean createNewFile()      创建一个新的空的文件
public boolean mkdir()              创建单级文件夹
public boolean mkdirs()             创建多级文件夹
public boolean delete()             删除文件、空文件夹
    
public File[] listFiles()       获取当前该路径下所有内容
public static File[] listRoots()                列出可用的文件系统根
public String[] list()                          获取当前该路径下所有内容
public String[] list(FilenameFilter filter)     利用文件名过滤器获取当前该路径下所有内容
public File[] listFiles()                获取当前该路径下所有内容
public File[] listFiles(FileFilter filter)      利用文件名过滤器获取当前该路径下所有内容
public File[] listFiles(FilenameFilter filter)  利用文件名过滤器获取当前该路径下所有内容

2 IO流的分类

流的方向

输入流(读取):把数据从其他设备上读取到内存中的流

输出流(写出):把数据从内存 中写出到其他设备上的流。

操作文件的类型

字节流:所有类型的文件,以字节为单位,读写数据的流。

字符流:只能操作纯文本文件,以字符为单位,读写数据的流。

3 字节流

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

InputStream 字节输入流

java.io.InputStream 抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。它定义了字节输入流的基本共性功能方法。

public void close()	 		关闭此输入流并释放与此流相关联的任何系统资源。    
public abstract int read()  从输入流读取数据的下一个字节。 
public int read(byte[] b)	从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
FileInputStream

操作本地文件的字节输入流,可以把本地文件中的数据读取到程序中\

构造方法

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
read(byte[] b)  每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回-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();
    }
}


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));
       }
		// 关闭资源
       fis.close();
    }
}

OutputStream 字节输出流

java.io.OutputStream 抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。

public void close()			关闭此输出流并释放与此流相关联的任何系统资源。  
public void flush()			刷新此输出流并强制任何缓冲的输出字节被写出。  
public void write(byte[] b)		将 b.length字节从指定的字节数组写入此输出流。  
public void write(byte[] b, int off, int len) 从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。  
public abstract void write(int b)		将指定的字节输出流。
FileOutputStream

java.io.FileOutputStream 类是文件输出流,用于将数据写出到文件。

操作本地文件的字节输出流,可以把程序中的数据写到本地文件中

构造方法

public FileOutputStream(File file)	创建文件输出流以写入由指定的 File对象表示的文件。 
public FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。  

当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。

public class FileOutputStreamConstructor throws IOException {
    public static void main(String[] args) {
   	 	// 使用File对象创建流对象
        File file = new File("a.txt");
        FileOutputStream fos = new FileOutputStream(file);
      
        // 使用文件名称创建流对象
        FileOutputStream fos = new FileOutputStream("b.txt");
    }
}
写出数据
write(int b)  					 每次可以写出一个字节数据
write(byte[] b) 				 每次可以写出数组中的数据
write(byte[] b, int off, int len)  每次写出从off索引开始,len个字节
    
public FileOutputStream(File file, boolean append) 创建文件输出流以写入由指定的 File对象表示的文件。 
public FileOutputStream(String name, boolean append)创建文件输出流以指定的名称写入文件.
参数中都需要传入一个boolean类型的值,`true` 表示追加数据,`false` 表示清空原有数据。这样创建的输出流对象,就可以指定是否追加续写
public class FOSWrite {
    public static void main(String[] args) throws IOException {
       // 使用文件名称创建流对象
       FileOutputStream fos = new FileOutputStream("fos.txt");     
      	// 写出数据
      	fos.write(97); // 写出第1个字节
      	fos.write(98); // 写出第2个字节
      	fos.write(99); // 写出第3个字节
      	// 关闭资源
       fos.close();
    }
}

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();
    }
}

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();
    }
}


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();
    }
}

4 字符流

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

字符流的底层其实就是字节流

字符流 = 字节流 + 字符集

输入流:一次读一个字节,遇到中文一次读多个字节

输出流:底层会把数据按照指定的编码方式进行编码,编程字节再写到文件中

Reader 字符输入流

java.io.Reader抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入流的基本共性功能方法。

public void close()			关闭此流并释放与此流相关联的任何系统资源。    
public int read()			从输入流读取一个字符。 
public int read(char[] cbuf)  从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。
FileReader

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
read(char[] cbuf)每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-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();
    }
}

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();
    }
}

Write 字符输出流

java.io.Writer 抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。它定义了字节输出流的基本共性功能方法。

void write(int c)				写入单个字符。
void write(char[] cbuf) 		写入字符数组。 
abstract void write(char[] cbuf, int off, int len) 写入字符数组的某一部分,off数组的开始索引,len写的字符个数。 
void write(String str)			写入字符串。 
void write(String str, int off, int len)写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
void flush()		刷新该流的缓冲。  
void close()		关闭此流,但要先刷新它。 
FileWriter

FileWrite :操作本地文件的字符输出流

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)  每次可以写出一个字符数据
write(char[] cbuf)
write(char[] cbuf, int off, int len)  每次可以写出字符数组中的数据,用法类似FileOutputStream
write(String str)write(String str, int off, int len)  每次可以写出字符串中的数据,更为方便
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();
    }
}

public class FWWrite {
    public static void main(String[] args) throws IOException {
       // 使用文件名称创建流对象
       FileWriter fw = new FileWriter("fw.txt");     
      	// 字符串转换为字节数组
      	char[] chars = "黑马程序员".toCharArray();
      	// 写出字符数组
      	fw.write(chars); // 黑马程序员
		// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
       fw.write(b,2,2); // 程序
      	// 关闭资源
       fos.close();
    }
}


public class FWWrite {
    public static void main(String[] args) throws IOException {
       // 使用文件名称创建流对象
       FileWriter fw = new FileWriter("fw.txt");     
      	// 字符串
      	String msg = "黑马程序员";
      	// 写出字符数组
      	fw.write(msg); //黑马程序员
		// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
       fw.write(msg,2,2);	// 程序
       // 关闭资源
       os.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个字符
        fw.flush();
        fw.write('新'); // 继续写出第2个字符,写出成功
        fw.flush();
      
      	// 写出数据,通过close
        fw.write('关'); // 写出第1个字符
        fw.close();
        fw.write('闭'); // 继续写出第2个字符,【报错】java.io.IOException: Stream closed
        fw.close();
    }
}

5 字节缓冲流

底层自带了长度为8192的缓冲区提高性能

BufferedInputStream 字节缓冲输入流

BufferedOutputStream 字节缓冲输出流

构造方法

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 static void main(String[] args) throws Exception{
        // 1.创建缓冲流的对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("IOStream-03\\BufferedInputOrOutputStream.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("IOStream-03\\BufferedInputOrOutputStream_copy2.txt"));

        // 2.拷贝(一次读写多个字节)
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }
        // 3.释放资源
        bos.close();
        bis.close();
    }

创建字节缓冲区的时候关联了基本流,表明了真正从文件中读取数据的还是基本流,读取后再交给缓冲流。缓冲区中默认有8192字节大小的缓冲区。写出同理。

注意:缓冲输入流和缓冲输出流的两个缓冲区是不同的,不是同一个。

使用字节缓冲流默认是不用手动关闭基本流的,关闭缓冲流的时候自动帮我们关闭了基本流

6 字符缓冲流

BufferedReader 字符缓冲输入流

BufferedWriter 字符缓冲输出流

构造方法

public BufferedReader(Reader in)    创建一个 新的缓冲输入流。 
public BufferedWriter(Writer out)   创建一个新的缓冲输出流。
// 创建字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
// 创建字符缓冲输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

特有方法

字符缓冲流的基本方法与普通字符流调用方式一致,它们具备的特有方法。

BufferedReaderpublic String readLine()  读一行文字。 
BufferedWriterpublic 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();
    }
}

7 转换流

转换流是字符流和字节流之间的桥梁

在IDEA中,使用FileReader 读取项目中的文本文件。由于IDEA的设置,都是默认的UTF-8编码,所以没有任何问题。但是,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。

public class ReaderDemo {
    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("E:\\File_GBK.txt");
        int read;
        while ((read = fileReader.read()) != -1) {
            System.out.print((char)read);
        }
        fileReader.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(new FileOutputStream(FileName2),"GBK");
       // 写出数据
      	osw2.write("你好");// 保存为4个字节
       osw2.close();
    }
}

8 序列化流

属于字节流的一种

输入流 — 反序列化 — ObjectInputStream

输出流 — 序列化 — ObjectOutputStream

序列化

序列化的定义是:将一个对象编码成一个字节流(I/O);而与之相反的操作被称为反序列化。

将Java中的对象写到本地文件中

序列化的目的是为了方便数据的传递以及存储到磁盘上(把一个Java对象写入到硬盘或者传输到网路上面的其它计算机,这时我们就需要将对象转换成字节流才能进行网络传输。对于这种通用的操作,就出现了序列化来统一这些格式)。

简单来说序列化就是一种用来处理对象流的机制。将对象转化成字节序列后可以保存在磁盘上,或通过网络传输,以达到以后恢复成原来的对象。序列化机制使得对象可以脱离程序的运行而独立存在。

使用场景:所有可在网络上传输的对象都必须是可序列化的.Redis 将对象当做字符串存储的时候,如果对象实现了序列化,则只需要将对象直接存储即可(java会自动将对象转换成序列化后的字节流);否则需要自己将对象转换成 json 字符串存储,不过 json 字符串相对更加节省内存空间一些。

Student

public class Student implements Serializable {
    // 版本号
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    // set get 构造 toString()
}
ObjectOutputStream

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

构造方法

public ObjectOutputStream(OutputStream out)		创建一个指定OutputStreamObjectOutputStream
public final void writeObject(Object obj)     把对象序列化(写出)到文件中去
FileOutputStream fileOut = new FileOutputStream("employee.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
序列化操作
  1. 使用序列化流将对象写到文件时,需要让JavaBean类实现Serializable接口,否则会出现NotSerializableException异常
  2. 序列化流写到文件中的数据不能更改,一旦更改就无法再次读回
  3. 序列化对象后,修改了JavaBean类,再次反序列化会出问题, 给JavaBean类添加 private static final long serialVersionUID即可。
  4. 如果一个对象中的某个成员变量不想被序列化,给该成员变量加transient关键字修饰即可。
public class Employee implements java.io.Serializable {
    public String name;
    public String address;
    public transient int age; // transient瞬态修饰成员,不会被序列化
    public void addressCheck() {
      	System.out.println("Address  check : " + name + " -- " + address);
    }
}

写出对象方法

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

public static void main(String[] args) throws Exception {
        // 创建序列化对象
        Student student = new Student("张三", 20);

        // 创建序列化流的对象/对象操作输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("IOStream-05\\Student_Serialize.txt"));
        // 写出数据
        oos.writeObject(student);
        // 释放资源
        oos.close();

    }
ObjectInputStream

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

方法

public ObjectInputStream(InputStream in)    创建一个指定InputStreamObjectInputStream
public Object readObject()              把序列化到本地文件中的对象,读取到程序中来
public static void main(String[] args) throws Exception {
        // 1.创建反序列化流的对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("IOStream-05\\Student_Serialize.txt"));

        // 2.读取数据
        Student o = (Student) ois.readObject();

        // 3.打印对象
        System.out.println(o);

        // 4.释放资源
        ois.close();
    }
序列化集合
public class SerTest {
	public static void main(String[] args) throws Exception {
		// 创建 学生对象
		Student student = new Student("老王", "laow");
		Student student2 = new Student("老张", "laoz");
		Student student3 = new Student("老李", "laol");

		ArrayList<Student> arrayList = new ArrayList<>();
		arrayList.add(student);
		arrayList.add(student2);
		arrayList.add(student3);
		// 序列化操作
		// serializ(arrayList);
		
		// 反序列化  
		ObjectInputStream ois  = new ObjectInputStream(new FileInputStream("list.txt"));
		// 读取对象,强转为ArrayList类型
		ArrayList<Student> list  = (ArrayList<Student>)ois.readObject();
		
      	for (int i = 0; i < list.size(); i++ ){
          	Student s = list.get(i);
        	System.out.println(s.getName()+"--"+ s.getPwd());
      	}
	}

	private static void serializ(ArrayList<Student> arrayList) throws Exception {
		// 创建 序列化流 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
		// 写出对象
		oos.writeObject(arrayList);
		// 释放资源
		oos.close();
	}
}

  1. 本文参考 黑马程序员Java中IO章节,点我直达 ↩︎

  • 20
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值