Summary of JavaI/O and serialization methods

1. Use I\O to operate files

  1. Manipulate file or directory attributes

                                 Constructor of the Flie class

method illustrate
Flie(string pathname) Constructs a file with the specified file path
File(string dir,string subpath) Create a file with the file name under the specified target, with the path in front and the file name in the back
File(file parent,string subpath) Construct a file object based on a file object and a word file, the parent specifies the directory file, and the subpath parameter specifies the file name

                                 Common methods of the file class

method illustrate
boolean exists() Test for file existence
string GetAbsolutePath() Returns the absolute path of the file represented by this object
string getname() Returns the name of the file represented by this object
string getparent() Returns the previous level of this File object's pathname, or null if there is no previous level
Boolean delete() delete the file specified by this object
Boolean createNewFile() Create empty files instead of folders
Boolean isDirectory() Tests whether the secondary File object represents a directory
Boolean mkdir() Creates a directory whose path is specified by the current File object
Boolean mkdirs() Create a directory including the parent class

The steps of using the File class to manipulate file and directory attributes are generally:
(1) Introduce the File class
import java.io.File;
(2) Construct a file object
File file = new File("text.txt");
(3) Use Methods of the File class access properties of files or directories (file.method)

2. Know java stream

(1) Stream refers to a string of flowing characters, following first-in, first-out.
(2) Streams are divided into input streams and output streams. It is further divided into character stream and byte stream.
(3) The base class of the byte stream is the InputStream class and the OutputStream class. They are abstract classes
(4) The base classes of character streams are Reader class and Writer class, they are abstract classes.

                                 Common methods of the InputStream class

method illustrate
int read() Read the next byte of data from the input stream
int read(byte[]b) Read data from the input stream and store the data in the buffer array b, return the number of bytes read
int read(byte[]b,int off,int len) Read up to len bytes from the input stream and store them in array b, starting from off
void close() close input stream

Commonly used subclasses of InputStream are FileInputStream, which is used to read data from files.

                                 Common methods of the OutputStream class

method illustrate
void write(int c) writes the specified byte data to this output stream
void write(byte[]b) writes all bytes in array b to this output stream
void write(byte[]b,int off,int len) Output the byte data whose length is len starting from the offset off in the byte data to the output stream
void close() close output stream

The commonly used subclass of OutputStream is FileOutputStream, which is used to write data to the file.

                                 Common methods of the Reader class

method illustrate
int read() Reads a single character from the input stream and returns the character data read
int read(byte[]b) Read at most b.length characters from the input stream, store them in the array b, and return the number of characters actually read
int read(byte[]b,int off,int len) Read up to len characters from the input stream, save them in character data b, the saved position starts from off, and return the number of characters actually read
void close() close output stream

The commonly used subclasses of Reader are BuffereReader, which is used to add character buffers.

                                    Common methods of the Writer class

method illustrate
void write(string str) Output the characters contained in the str string to the specified output stream
void write(string str,int off,int len) Output multiple characters with a length of len starting from the off position in the str string to the output stream
void close() close output stream
void flush() Flush the output stream

A commonly used subclass of Writer is BufferWriter, which is used to buffer data to a character output stream.

3. Read and write text files

(1). Use the byte stream to read the text file
A. Use the byte stream class FileInputStream to read the text file,
a subclass of the FileInputStream abstract class. Called the file input stream, it is a subclass of the byte input stream InputStream abstract class. Its role is to input the data in the file into the internal memory (memory), which can be used to read the data in the text file. The specific implementation steps are as follows:

(1) Import related classes
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
(2) Construct a file input stream object
InputStream fileObject = new FileInputStream("tex.txt")
( 3) Use the file input stream method to read the data of the text file.
fileObject.available();
fileObject.read();
(4) Close the file input stream object
fileObject.close();

(2) Use byte stream FileOutputStream to write text files
FileOutputStream is called file output stream, which is a subclass of byte input stream OutputStream abstract class. Its function is to output the data in the memory to a file, and you can use it to write the data in the memory to a text file. The specific steps are:

(1)导入相关的类
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
(2)构造一个文件输出流对象
OutputStream fos = new FileOutputStream(“tex.txt”)
(3)利用文件输出流的方法把数据写入到文本文件中。
string str = “好好学习天天向上”
byte[] words = str.getBytes();
fos.write(words,0,words.length);
(4)关闭文件输出流
fos.close();

(2).使用字符流读写文本文件
B.使用字符流BufferedReader和FileReader读文本文件
BufferedReader和FileReader两个类都是Reader抽象类的子类,他们可以通过字符流的方式读取文件,并使用缓冲区,提高了读文本文件的效率。 其具体步骤如下:

(1)导入相关的类
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
(2)构造一个BuffereReader对象
FileReader fr = new FileReader(“mytext.txt”);
BufferedReader br = new BufferedReader(fr) ;
(3)利用BufferedReader类的方法读取文本文件的数据。
br.readLine();
(4)关闭相关流对象
fr.close();

(2)使用字符流BufferedWriter和FileWriter读文本文件
BufferedWriter和FileWriter两个类都是Writer抽象类的子类,他们可以通过字符流的方式并通过缓冲区把数据写入到文本文件,提高了写文本文件的效率。 其具体步骤是:

(1)导入相关的类
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
(2)构造一个BufferedWriter对象
FileWriter fw = new FileWriter(“mytext.txt”);
BufferedWriter bw = new BufferedWriter(fw)
(3)利用BuffereReader类的方法读取文本文件的数据。
bw.write(“hello”);
(4)关闭清空相关流对象
bw.flush();
bw.close();
fw.close();

4. 序列化

(1)序列化保存对象信息

对象序列化的步骤很简单,可以概括如下两大步:

(1)创建一个对象输出流,他可以包装一个其他类型的输出流。
(2)通过对象输出流的writeobject()方法写对象,也就是输出可序列化对象。

###(2) 反序列化获取对象信息
反序列化的步骤大致概括为一下两步。

(1)创建一个对象输入流,它可以包装一个其他类型的输入流。
(2)通过对象输入流的readobject()方法读取对象,该方法返回一个object类的对象。

二、代码示例

1、I/O示例:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.OutputStream;

public class Main_1 {
    
    
	public static void main(String[] args) {
    
    
		try {
    
    
			//创建"我的青春我做主.txt"文本;
			File file = new File("D:\\我的青春我做主.txt"); //引入对象file
			File file1 = new File("D:\\我的青春我做主1.txt");
			file.createNewFile();//创建文本文档
			file1.createNewFile();
			//查看文本是否存在
			System.out.println(file.exists());
			//用字节流向文本输入信息
			OutputStream fos = new FileOutputStream(file);  //创建文本写入对象
			String str ="青春飞扬,肆意的岁月!"; // 要写入的文字
			fos.write(str.getBytes());   //将文字输入文本
			fos.close(); //关闭字节输入流
			//用字节输出流读取文本内容
			FileInputStream fis = new FileInputStream(file);
			int data;
			System.out.println("可读取的字节数为:" + fis.available());//fis.available():可读取的字节数
			System.out.println("文件内容为:");
			//输出读取的内容(显示为字节)
			while((data = fis.read())!= -1){
    
    
				System.out.print(data + " ");
			}
            fis.close();//关闭字节输出流
            /**
             * 使用字符输入流:向文本中输入内容
             */
             FileWriter fw = new FileWriter(file);   //FileWriter 是Writer类的子类,通常和BufferedReader合用,建立缓冲区。
             BufferedWriter bw = new BufferedWriter(fw);  //BufferedWriter,是Writer类的子类,通常和FileWriter合用,建立缓冲区。
             //向文本输入
             bw.write("自由的世界,无敌的人生!");
             bw.write("无敌是多么多么,寂寞!");
             //输入文本一行
             bw.newLine();
             bw.write("呜哈哈哈哈!!!!");
             bw.newLine();
             //刷新,文本读取文字
             bw.flush();
             bw.close();
             fw.close();
            /**
             * 字符输出流:从文本中读取文本内容
             */
           FileReader fr = new FileReader(file); 
// FileReader 是Reader类的子类,通常和BufferedReader合用,建立缓冲区。
           BufferedReader br = new BufferedReader(fr); 
           // BufferedReader 是Reader类的子类,通常和FileReader合用,建立缓冲区。
            //简略写法: BufferedReader br = new BufferedReader(new FileReader(file));
           // br.readLine(); 读取文本中的字符串
           String line = br.readLine();
           //输出读入的内容(显示为字符)
           while(line != null){
    
    
        	   System.out.println("\n"+line);
        	   line = br.readLine(); //此句的作用是输出多个字符串语句
           }
           //关闭字符输入流
           br.close();
           fr.close()/**
            * 将file的内容复制到file1中
            */
            FileInputStream fi = new FileInputStream(file);
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

2、序列化示例

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Main3 {
    
    
	public static void main(String[] args) {
    
    
		ObjectOutputStream oos = null;
		try {
    
    
			//创建ObjectOutputStream输出流
			oos = new ObjectOutputStream(new FileOutputStream("D:\\javaIO\\test2.txt"));
			Student stu = new Student("安娜",30,"女");
			Student stu1 = new Student("张珊",15,"女");
			Student stu2 = new Student("李斯",26,"女");
			ArrayList <Student> list = new ArrayList <Student>();
			list.add(stu);
			list.add(stu1);
			list.add(stu2);
			//对象序列化,写入输出流
			oos.writeObject(list);
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}finally{
    
    
			if(oos != null){
    
    
			try {
    
    
				oos.close();
			} catch (Exception e2) {
    
    
				e2.printStackTrace();
		  }
		}
	  }	
		ObjectInputStream ois = null;
		try {
    
    
			//创建ObjectInputStream 输入流
			ois = new ObjectInputStream(new FileInputStream("D:\\javaIO\\test2.txt"));
			//反序列化,进行强制类型转换
			ArrayList <Student> list = (ArrayList <Student>)ois.readObject();
			//输出生成后的对象信息
			for(Student stu:list){
    
    
				System.out.println("姓名为:" + stu.getName());
				System.out.println("年龄为:" + stu.getAge());
				System.out.println("性别为:" + stu.getSex());
			}
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}finally{
    
    
			if(ois != null){
    
    
				try {
    
    
					ois.close();
				} catch (Exception e2) {
    
    
					e2.printStackTrace();
				}
			}
		}
	}
}

Guess you like

Origin blog.csdn.net/Acompanys/article/details/105270570