Heim  >  Artikel  >  Java  >  IO – Konvertierungs-Stream, Druck-Stream, Serialisierungsbeispiele, detaillierte Erklärung

IO – Konvertierungs-Stream, Druck-Stream, Serialisierungsbeispiele, detaillierte Erklärung

零下一度
零下一度Original
2017-06-23 10:35:251395Durchsuche

Kodierung:

Verständliches in Unverständliches verwandeln
String str = "China";
byte[] bytes = str.getBytes( );
System.out.println(Arrays.toString(bytes));
Dekodierung:

Unverständliche Inhalte in verständliche Inhalte umwandeln
String s = new String(bytes) ;
System.out.println(s);
java.io.OutputStreamWriter erweitert Writer
OutputStreamWriter: Stream konvertieren
Funktion: Es ist ein Zeichenstrom in ein Wort. Eine Brücke zur Drosselung können Sie Geben Sie die Codierungstabelle an.

Von der öffentlichen Mitgliedsmethode der übergeordneten Klasse Writer geerbt.
Schreiben Sie ein Zeichen, schreiben Sie ein Zeichenarray, schreiben Sie einen Teil des Zeichenarrays, schreiben Sie eine Zeichenfolge, schreiben Sie einen Teil davon Zeichen, Aktualisieren, schließen

Konstruktor:
OutputStreamWriter(OutputStream out, String charsetName) Erstellt einen OutputStreamWriter mit dem angegebenen Zeichensatz.
Parameter:
OutputStream out: Byte-Ausgabestream (schreibt die konvertierten Bytes in die Datei)
Kann in FileOutputStream übergeben werden
String charsetName: Name der Codierungstabelle
Kann in einer Codierungstabelle übergeben werden Name im Zeichenfolgenformat, z. B. „GBK“, „utf-8“..., der Name der Codierungstabelle unterscheidet nicht zwischen Groß- und Kleinschreibung. Wenn er nicht geschrieben wird, wird standardmäßig die Systemcodetabelle verwendet

Verwendungsschritte:
1. Erstellen Sie den Zeichenausgabestream FileOutputStream und binden Sie das Ziel der Daten
2. Erstellen Sie das OutputStreamWriter-Objekt des Konvertierungsstreams und übergeben Sie den FileOutputStream und den angegebenen Codierungstabellennamen im Konstruktor
3. Aufruf die Methode zum Schreiben von Daten im OutputStreamWriter, schreibt die Daten in den Speicherpuffer
4. Geben Sie die Ressourcen frei und aktualisieren Sie die Daten in der Datei

 1 public static void main(String[] args) throws IOException { 2         //write_GBK(); 3         write_UTF8(); 4     } 5  6     /* 7      * 使用转换流OutputStreamWriter,写UTF-8格式的文件 8      */ 9     private static void write_UTF8() throws IOException {10         //1.创建字符输出流FileOutputStream,绑定数据的目的地11         FileOutputStream fos = new FileOutputStream("utf-8.txt");12         //2.创建转换流OutputStreamWriter对象,构造方法中传入FileOutputStream和指定的编码表名称13         OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");14         //3.调用OutputStreamWriter中写数据的方法,把数据写入到内存缓冲区中15         osw.write("你好");16         //4.释放资源,并把数据刷新到文件中17         osw.close();18     }19 20     /*21      * 使用转换流OutputStreamWriter,写GBK格式的文件22      */23     private static void write_GBK() throws IOException {24         //1.创建字符输出流FileOutputStream,绑定数据的目的地25         FileOutputStream fos = new FileOutputStream("gbk.txt");26         //2.创建转换流OutputStreamWriter对象,构造方法中传入FileOutputStream和指定的编码表名称27         //OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");28         OutputStreamWriter osw = new OutputStreamWriter(fos);29         //3.调用OutputStreamWriter中写数据的方法,把数据写入到内存缓冲区中30         osw.write("你好");31         //4.释放资源,并把数据刷新到文件中32         osw.close();33     }

java.io. InputStreamReader erweitert Reader
* InputStreamReader-Stream: Es handelt sich um eine Brücke vom Byte-Stream zum Zeichen-Stream. Sie können die Codierungstabelle angeben
*
* Von der öffentlichen Member-Methode der übergeordneten Klasse Reader geerbt
*. int read() liest ein einzelnes Zeichen.
* int read(char[] cbuf) Liest Zeichen in ein Array.
* abstract void close() Schließt den Stream und gibt alle damit verbundenen Ressourcen frei.
*
* Konstruktor:
* InputStreamReader(InputStream in) Erstellt einen InputStreamReader mit dem Standardzeichensatz.
* InputStreamReader(InputStream in, String charsetName) erstellt einen InputStreamReader mit dem angegebenen Zeichensatz.
* Parameter:
* InputStream in: Byte-Eingabestream (lesen Sie die in der Datei gespeicherten Bytes)
* Sie können FileInputStream übergeben
* String charsetName: Name der Codierungstabelle
* Sie können Übergeben Sie einen Codierungstabellennamen im Zeichenfolgenformat, z. B. „GBK“, „utf-8“ .... Beim Codierungstabellennamen wird die Groß-/Kleinschreibung nicht beachtet. Wenn er nicht geschrieben wird, wird standardmäßig die Systemcodetabelle verwendet
*.
* Verwendungsschritte:
* 1. Erstellen Sie ein Byte-Eingabestream-FileInputStream-Objekt und binden Sie die Datenquelle
* 2. Erstellen Sie ein InputStreamReader-Objekt für den Konvertierungsstream, übergeben Sie in der Konstruktionsmethode den FileInputStream und den angegebenen Codierungstabellenname
* 3. Verwenden Sie die InputStreamReader-Methode zum Lesen von Daten, lesen Sie Daten
* 4. Geben Sie Ressourcen frei
*
* Hinweis: Der in der Konstruktionsmethode angegebene Codierungsname muss mit dem übereinstimmen Andernfalls werden verstümmelte Zeichen angezeigt

 1 public static void main(String[] args) throws IOException { 2         //read_GBK(); 3         read_UTF8(); 4     } 5  6     /* 7      * 使用InputStreamReader读取UTF-8格式文件 8      */ 9     private static void read_UTF8() throws IOException {10         //1.创建字节输入流FileInputStream对象,绑定数据源11         FileInputStream fis = new FileInputStream("utf-8.txt");12         //2.创建转换流InputStreamReader对象,构造方法中,传入FileInputStream和指定的编码表名称13         //InputStreamReader isr = new InputStreamReader(fis,"GBK");//乱码:浣犲ソ14         InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//你好15         //3.使用InputStreamReader读取数据的方法,读取数据16         //int read() 读取单个字符。 17         int len = 0;18         while((len = isr.read())!=-1){19             System.out.print((char)len);20         }21         //4.释放资源22         isr.close();23     }24 25     /*26      * 使用InputStreamReader读取GBK格式文件27      */28     private static void read_GBK() throws IOException {29         //1.创建字节输入流FileInputStream对象,绑定数据源30         FileInputStream fis = new FileInputStream("gbk.txt");31         //2.创建转换流InputStreamReader对象,构造方法中,传入FileInputStream和指定的编码表名称32         //InputStreamReader isr = new InputStreamReader(fis,"GBK");33         InputStreamReader isr = new InputStreamReader(fis);//不指定,默认使用GBK34         //3.使用InputStreamReader读取数据的方法,读取数据35         //int read() 读取单个字符。 36         int len = 0;37         while((len = isr.read())!=-1){38             System.out.print((char)len);39         }40         //4.释放资源41         isr.close();42     }

对象的序列化和反序列化
* 对象的序列化:把对象以流的方式写入到文件中保存
* 对象的反序列化:把文件中保存的对象,以流的方式读取出来
对象的反序列化:把文件中保存的对象,以流的方式读取出来
*
* 构造方法:
* ObjectInputStream(InputStream in) 创建从指定 InputStream 读取的 ObjectInputStream。
* 参数:
* InputStream in:字节流,可以传入FileInputStream
*
* 读对象的方法:
* Object readObject() 从 ObjectInputStream 读取对象。
*
* 使用步骤:
* 1.创建字节输入流FileInputStream,绑定数据源
* 2.创建反序列化流ObjectInputStream,构造方法中传入FileInputStream
* 3.使用ObjectInputStream中的方法readObject,读取文件中保存的对象
* 4.释放资源
* 5.打印对象
*
* 注意:
* 方法readObject,会抛出ClassNotFoundException(没有class文件异常)
* 反序列化的前提,必须有对象的class文件存在
对象的序列化:把对象以流的方式写入到文件中保存
* 构造方法:
* ObjectOutputStream(OutputStream out)  创建写入指定 OutputStream 的 ObjectOutputStream。
*  参数:
* OutputStream out:字节流,可以传入FileOutputStream
*
* 写对象的方法:
* void writeObject(Object obj) 将指定的对象写入 ObjectOutputStream。
*
* 使用步骤:
* 1.创建对象,并赋值
* 2.创建字节输出流对象FileOutputStream,绑定数据目的地
* 3.创建序列化流ObjectOutputStream对象,构造方法中传入FileOutputStream
* 4.使用ObjectOutputStream中的方法writeObject,把对象写入到文件中
* 5.释放资源
*
* 注意:
* 要序列化的类如果没有实现Serializable接口,会抛出NotSerializableException异常
*/
类通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化

Serializable接口:称之为标记型接口
类只有实现了Serializable才能序列化和反序列化,不实现就不能
去市场卖肉,肉上有一个蓝色的戳(检测合格),买回去干什么有不同的吃的方式
java.lang.Cloneable:标记型接口
类实现了Cloneable就能复制,不实现就不能

序列化和反序列的是对象,如果对象中有静态的属性,可以序列化吗?
静态属于类,不属于对象,不能序列化
不管是静态属性和非静态属性都有默认值
age默认值是0,又是静态属性,不能序列化,使用默认值0
瞬态关键字transient:作用,阻止成员变量序列化

打印流:
* 字节打印流:PrintStream extends OutputStream
* 字符打印流:PrintWriter extends Writer
*
* 两个打印流中的方法,完全一致:
* void print(Object obj): 输出任意类型的数据,
* void println(Object obj): 输出任意类型的数据,自动写入换行操作
*
* 构造方法,就是打印流的输出目的端
* PrintStream
* 构造方法目的地:接收File类型,接收字符串文件名,接收字节输出流OutputStream
* PrintWriter
* 构造方法目的地:接收File类型,接收字符串文件名,接收字节输出流OutputStream,
* 接收字符输出流Writer
*
* 注意事项:
* 字节流写入数据的时候,会直接把数据写入到文件中
* 字符流写入数据的时候,会把数据写入到内存缓冲区中,必须刷新或者关闭,才会把数据由缓冲区刷新到文件中
*/''

 1 public static void main(String[] args) throws IOException { 2         System.out.println(97); 3         method_04(); 4     } 5  6     /* 7      * 字符打印流的自动刷新功能 8      * 自动刷新功能的使用必须满足3个条件: 9      *     1.字符打印流的输出的目的地必须是一个流对象(字符,字节)10      *     2.字符打印流构造方法的参数autoFlush必须是true11      *     3.必须使用 println、printf 或 format 方法中的一个才能实现12      * 
13      * 包含自动刷新的构造方法:14      *     PrintWriter(OutputStream out, boolean autoFlush) 
15      *  PrintWriter(Writer out, boolean autoFlush) 
16      *  
17      * 我们可以把字符串的目的地和File类的目的地转换为流,开启自动刷新 
18      */19     private static void method_04() throws IOException {20         PrintWriter pw = new PrintWriter(new FileWriter("6.txt"),true);21         pw.print("不能自动刷新");22         pw.println("会自动把缓冲区中所有的内容刷新到文件中");23     }24 25     /*26      * 打印流,输出目的地,是流对象27      * 可以是字节输出流,也可以是字符输出流28      * OutputStream Writer29      */30     private static void method_03() throws IOException {31         FileOutputStream fos = new FileOutputStream("3.txt");32         ////The constructor PrintStream(FileWriter) is undefined33         //PrintStream ps = new PrintStream(new FileWriter("3.txt"));34         PrintStream ps = new PrintStream(fos);35         ps.println("字节打印流的输出目的地是一个字节流");36         ps.close();37         38         PrintWriter pw = new PrintWriter(new FileOutputStream("4.txt"));39         pw.println("字符打印流的输出目的地是一个字节流");40         pw = new PrintWriter(new FileWriter("5.txt"));41         pw.println("字符打印流的输出目的地是一个字符流");42         pw.close();43     }44 45     /*46      * 打印流,输出目的,String文件名47      */48     private static void method_02() throws FileNotFoundException {49         PrintWriter pw = new PrintWriter("2.txt");50         pw.println("字符打印流,必须的刷新");51         //pw.flush();52         pw.close();53     }54 55     /*56      * 打印流,向File文件对象的数据目的地写入数据57      * 方法 print println 原样输出58      * write方法 走编码表59      */60     private static void method_01() throws FileNotFoundException {61         File file = new File("1.txt");62         PrintStream ps = new PrintStream(file);63         //使用继承自父类的write方法写入数据64         ps.write(97);65         //使用自己特有的方法println/print写入数据66         ps.println(97);67         ps.println(true);68         ps.println("hello");69         ps.println(8.8);70         ps.println('中');71         ps.close();72     }

字符打印流的自动刷新功能
自动刷新功能的使用必须满足3个条件:
1.字符打印流的输出的目的地必须是一个流对象(字符,字节)
2.字符打印流构造方法的参数autoFlush必须是true
3.必须使用 println、printf 或 format 方法中的一个才能实现

包含自动刷新的构造方法:
PrintWriter(OutputStream out, boolean autoFlush)
 PrintWriter(Writer out, boolean autoFlush)

我们可以把字符串的目的地和File类的目的地转换为流,开启自动刷新
打印流,输出目的地,是流对象
可以是字节输出流,也可以是字符输出流
OutputStream Writer

java.io.Properties集合 extends Hashtable implements Map接口
*
* Properties集合的特点:
* 1.健和值默认都是String类型
* 2.集合中有自己特有的方法
* Object setProperty(String key, String value) 调用 Hashtable 的方法 put。
* String getProperty(String key) 用指定的键在此属性列表中搜索属性。  相当于Map集合中的get(key k)方法
* Set stringPropertyNames() 返回此属性列表中的键集.  相当于Map集合中的的keySet  
* 3.和IO流相结合的方法
* 使用store方法把集合中保存的临时数据,持久化到硬盘的文件中保存
* void store(OutputStream out, String comments)  
* void store(Writer writer, String comments)
* 使用load方法把硬盘文件中保存的键值对,读取出来,放入到Properties集合中  
* void load(InputStream inStream)
* void load(Reader reader)

 1 public static void main(String[] args) throws IOException { 2         method_03(); 3     } 4  5     /* 6      * 使用load方法把硬盘文件中保存的键值对,读取出来,放入到Properties集合中  
 7      *     void load(InputStream inStream) 8      *     void load(Reader reader) 9      *     方法的参数:10      *         InputStream inStream:不能读取包含中文的键值对11      *         Reader reader:可以读取包含中文的键值对12      * 
13      * 使用步骤:14      *     1.创建Properties集合15      *     2.创建字节输入流/字符输入对象,绑定数据源16      *     3.使用Properties中的方法load,读取文件中保存的键值对,把键值对保存到集合中17      *     4.释放资源18      *     5.遍历Properties集合19      * 
20      * 注意:21      *         prop.properties文件中使用#号可以注释一行22      *         prop.properties文件中key和value默认就是字符不用使用""23      *         prop.properties文件中key和value之间可以使用=连接也可以使用空格24      */25     private static void method_03() throws IOException {26         //1.创建Properties集合27         Properties prop = new Properties();28         //2.创建字节输入流/字符输入对象,绑定数据源29         FileReader fr = new FileReader("prop.properties");30         //3.使用Properties中的方法load,读取文件中保存的键值对,把键值对保存到集合中31         prop.load(fr);32         //4.释放资源33         fr.close();34         //5.遍历Properties集合35         for(String key : prop.stringPropertyNames()){36             String value = prop.getProperty(key);37             System.out.println(key+"="+value);38         }39     }40 41     /*42      * 使用store方法把集合中保存的临时数据,持久化到硬盘的文件中保存43      *     void store(OutputStream out, String comments)  
44      *     void store(Writer writer, String comments)45      *     方法的参数:46      *         OutputStream out:不能操作中文47      *         Writer writer:可以操作中文48      *         String comments:注释,保存数据的用途,可以写"",不能写中文,默认使用unicode编码49      * 使用步骤:50      *     1.创建Properties集合,添加数据51      *     2.创建字节输出流或者字符输出流对象,绑定目的地52      *     3.使用Properties集合中的方法store把集合中的数据,写入到文件中53      *     4.释放资源54      */55     private static void method_02() throws IOException {56         //1.创建Properties集合,添加数据57         Properties prop = new Properties();58         prop.setProperty("a", "1");59         prop.setProperty("b", "2");60         prop.setProperty("中国", "1");61         //2.创建字节输出流或者字符输出流对象,绑定目的地62         FileWriter fw = new FileWriter("prop.properties");63         //3.使用Properties集合中的方法store把集合中的数据,写入到文件中64         prop.store(fw, "");65         //4.释放资源66         fw.close();67         68         FileOutputStream fos = new FileOutputStream("prop1.properties");69         prop.store(fos, "save date");//写入中文会出现乱码70         fos.close();71     }72 73     /*74      * 使用Properties集合中特有的方法,保存数据,遍历集合75      */76     private static void method_01() {77         Properties prop = new Properties();78         //Object setProperty(String key, String value) 调用 Hashtable 的方法 put。 79         prop.setProperty("a", "1");80         prop.setProperty("b", "2");81         prop.setProperty("c", "3");82         83         //Set<String> stringPropertyNames() 返回此属性列表中的键集.  相当于Map集合中的的keySet 84         Set<String> set = prop.stringPropertyNames();85         86         //遍历Set集合87         for (String key : set) {88             //String getProperty(String key) 用指定的键在此属性列表中搜索属性。  相当于Map集合中的get(key k)方法89             String value = prop.getProperty(key);90             System.out.println(key+"..."+value);91         }92     }

 

使用load方法把硬盘文件中保存的键值对,读取出来,放入到Properties集合中
* void load(InputStream inStream)
* void load(Reader reader)
* 方法的参数:
* InputStream inStream:不能读取包含中文的键值对
* Reader reader:可以读取包含中文的键值对
*
* 使用步骤:
* 1.创建Properties集合
* 2.创建字节输入流/字符输入对象,绑定数据源
* 3.使用Properties中的方法load,读取文件中保存的键值对,把键值对保存到集合中
* 4.释放资源
* 5.遍历Properties集合
*
* 注意:
* prop.properties文件中使用#号可以注释一行
* prop.properties文件中key和value默认就是字符不用使用""
* prop.properties文件中key和value之间可以使用=连接也可以使用空格
*/
使用store方法把集合中保存的临时数据,持久化到硬盘的文件中保存
* void store(OutputStream out, String comments)  
* void store(Writer writer, String comments)
* 方法的参数:
* OutputStream out:不能操作中文
* Writer writer:可以操作中文
* String comments:注释,保存数据的用途,可以写"",不能写中文,默认使用unicode编码
* 使用步骤:
* 1.创建Properties集合,添加数据
* 2.创建字节输出流或者字符输出流对象,绑定目的地
* 3.使用Properties集合中的方法store把集合中的数据,写入到文件中
* 4.释放资源

使用commons-IO中提供的工具类FileUtils
* static readFileToString(File file):读取文件内容,并返回一个String;
* static writeStringToFile(File file,String content):将内容content写入到file中;
* static copyFile(File srcFile, File destFile): 文件复制
* static copyDirectoryToDirectory(File srcDir,File destDir);文件夹复制
*
* 方法都是静态方法,可以通过类名直接使用
* 方法的参数都是File类型

 1 public static void main(String[] args) throws IOException { 2         //static readFileToString(File file):读取文件内容,并返回一个String; 3         //String s = FileUtils.readFileToString(new File("prop.properties")); 4         String s = FileUtils.readFileToString(new File("src/cn/itcsat/demo01/Demo01FileReader.java")); 5         System.out.println(s); 6          7         //static writeStringToFile(File file,String content):将内容content写入到file中; 8         FileUtils.writeStringToFile(new File("fileUitls.txt"), "FileUtils工具类的时候"); 9         10         //static copyFile(File srcFile, File destFile): 文件复制11         FileUtils.copyFile(new File("c:\\1.jpg"), new File("d:\\1.jpg"));12         13         //static copyDirectoryToDirectory(File srcDir,File destDir);文件夹复制14         FileUtils.copyDirectoryToDirectory(new File("c:\\demo"),new File("d:"));15     }

 

Das obige ist der detaillierte Inhalt vonIO – Konvertierungs-Stream, Druck-Stream, Serialisierungsbeispiele, detaillierte Erklärung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn