Java --- IO enhancement (2)

Familiar with memory 2021-01-21 15:57:28
java io enhancement


Converted flow

* Conversion stream function 1: Act as a bridge between byte stream and character stream

demand : Simulation English chat program , requirement : (1) Enter English characters from the keyboard , For each line recorded, convert it to uppercase and output it to the console ; (2) Save chat records to a byte stream file .

requirement 1 Design analysis of :

1) You need to receive input from the keyboard , Have to use System.in, It's a byte input stream InputStream; 2) You need to deal with characters , You can convert bytes into characters by yourself , You can also use character stream ; 3) It needs to be similar readLine The function of , And this method is in the character stream BufferedReader There is ( And this class has a buffer ). Sum up , It is more reasonable to use conversion stream to convert bytes into character stream , That is to use InputStreamReader

requirement 2 Design analysis of :

1) You need to save character data to a byte stream file by line ; 2) The character stream uses BufferedWriter More appropriate , Because it has the newLine Methods and can achieve efficient ; 3) Byte stream file , It has to be adopted FileOutputStream. Sum up , It is reasonable to use conversion stream to convert characters into byte stream , That is to use OutputStreamWriter

Code implementation :

package io.transfer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class TranStreamDemo {
public static void main(String[] args) throws IOException {
// Input
InputStream in = System.in;
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
// Output
OutputStream out = new FileOutputStream("chat.txt");
OutputStreamWriter osw = new OutputStreamWriter(out);
BufferedWriter bw = new BufferedWriter(osw);
String line = null;
while( (line=br.readLine())!=null){
if("over".equals(line)){
// Develop good code habits : call String Method in , Put the constant string first , Prevent variables from being null And lead to the exception
break;
}
System.out.println( line.toUpperCase() );
bw.write(line);
bw.newLine();
bw.flush();// The character stream is buffered , Must brush buffer
}
}
}

Converted flow

(InputStreamReader and OutputStreamWriter)

* Conversion stream function 2: Character encoding conversion

use FileWriter Code by default FileOutputStream+ Default code table

Use the conversion stream to code by default OutputStreamWriter + FileOutputStream + Default code table

Encode in the specified encoding mode by using the conversion stream OutputStreamWriter + FileOutputStream + Specify the encoding table

Decode in the specified encoding mode by using the converted stream InputStreamReader + FileInputStream + Specify the encoding table

Code implementation :

package io.transfer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class TranStreamDemo2 {
public static void main(String[] args) {
try {
//readTextDecoding1();
//readTextDecoding2();
writeTextEncoding();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeTextEncoding() throws IOException {
// The first one is : FileWriter+ Default code table
FileWriter fw = new FileWriter("files\\w_utf-8.txt");// The encoding of the file is determined by the platform ( Such as MyEclipse or dos window ) set , Is not necessarily utf-8
fw.write(" Make a little progress every day ...");
fw.close();
// The second kind : OutputStreamWriter+ Default code table
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("files\\w_utf-8_2.txt"));// The encoding of the file is determined by the platform ( Such as MyEclipse or dos window ) set , Is not necessarily utf-8
osw.write(" The next day, make a little progress ...");// Niuer
osw.close();
// The third kind of : OutputStreamWriter+ Specify the encoding table
OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("files\\w_utf-8_3.txt"),"utf-8");// The encoding of the file must be utf-8, Because it's our own designation
osw2.write(" The next day, make a little progress ...");
osw2.close();
}
private static void readTextDecoding1() throws IOException {
FileReader fr = new FileReader("files\\utf-8.txt");// Use the default encoding table to decode
char[] cbuf = new char[10];
int len=0;
while( (len=fr.read(cbuf))!=-1){
String str = new String(cbuf,0,len);
System.out.print(str);
}
fr.close();
}
private static void readTextDecoding2() throws IOException {
//InputStreamReader isr = new InputStreamReader(new FileInputStream("files\\gbk.txt"));// If no encoding table is specified , The default
// Use the conversion stream to specify the decoding table itself ---- As long as the encoding table of the file is the same as the decoding table specified here , There will be no garbled code
//InputStreamReader isr = new InputStreamReader( new FileInputStream("files\\gbk.txt"), "gbk"); //ok
//InputStreamReader isr = new InputStreamReader( new FileInputStream("files\\utf-8.txt"), "gbk");// The statement
InputStreamReader isr = new InputStreamReader( new FileInputStream("files\\utf-8.txt"), "utf-8");//ok
char[] cbuf = new char[20];
int len = isr.read(cbuf);
String str = new String(cbuf,0,len);
System.out.println(str);
isr.close();
}
}

Print stream

* The characteristics of print stream :

1) Only the output has no input .PrintStream It's a byte print stream ,PrintWriter It's a character print stream . 2) It can print all kinds of data conveniently “ Value representation ”, Provides a series of printing functions ( Only it has , None of the other streams .) 3) Unlike other output streams , It will never be thrown IOException abnormal ( Except for the construction method ), The exception is internally resolved and the internal flag is set . 4) Can be created with automatic refresh function , You can use println() Method . 5)( In the constructor ) Can specify character set encoding .

* About automatic refresh of print stream

autoFlush - boolean Variable ; If true, be println、printf or format Method will flush the output buffer . * — In fact, it's because these methods help us call out.flush().

Code implementation :

// demonstration PrintStream Class automatically refresh function

package io.print;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
*
* @author Chen Haoxiang
*
* 2016-4-24
*/
// demonstration PrintStream Class automatically refresh function
public class PrintStreamDemo {
public static void main(String[] args) {
try {
demo1();
demo2();
for(int i=0;i<10;i++){
System.out.println(i);
}
// There's no output at the screen terminal , Because it's running demo2();
// hold System.out The output destination of is changed from screen to log file
} catch (IOException e) {
e.printStackTrace();
}
}
// hold System.out The output destination of is changed from the screen to the log file
private static void demo2() throws IOException {
FileOutputStream font = new FileOutputStream("log.txt");
PrintStream out = new PrintStream(font,true);
System.setOut(out);
}
private static void demo1() throws IOException {
PrintStream out =new PrintStream("print.txt");
//out.write() Write only one byte ( The binary 8 position ) Information about , If the parameter is larger than a byte range ,
// In fact, only the last byte of data will be written
out.write(97);
out.write(353);
// The last byte is 97, So what's written is a character 'a'---- What is written is the representation of the value
System.out.write(353);// Output 'a'
System.out.flush();
out.println(345);// Convert parameters to string output
// The last sentence is equivalent to out.write( String.valueOf(i) )
//※ All in all ,PrintStream of use write() The output is byte data and only one byte at a time , and print() The output is the representation of the value of the data, that is, converted to string output .
//JSP Medium out Objects are of this type . To output byte data in binary format such as picture declaration, you must use write(), And output page data ( character ) It is necessary to use print() or println()
}
}

// demonstration PrintWriter Class automatically refresh function

package io.print;
import java.io.IOException;
import java.io.PrintWriter;
/**
*
* @author Chen Haoxiang
*
* 2016-4-24
*/
// demonstration PrintWriter Class automatically refresh function
public class PrintStreamDemo2 {
public static void main(String[] args) {
demo1();
try {
demo2();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void demo1() {
// It doesn't refresh automatically by default
PrintWriter out =new PrintWriter(System.out);
out.print("Hello World");// Will not automatically refresh
out.println("Hello World");// Will not automatically refresh
out.flush();// Manually refresh
}
private static void demo2() throws IOException {
// Set auto refresh
PrintWriter out = new PrintWriter(System.out,true);
out.print("Hello World");// Will not automatically refresh
out.println("Hello World");// Meeting ---- because println() Internal call out.flush()
out.print("Hello3 \n");// Can't
out.print("Hello3 \r\n");// Can't
out.printf("%s", "Hello4");// Meeting
/* All in all :
* autoFlush - boolean Variable ; If true, be println、printf or format Method will flush the output buffer .
* --- In fact, it's because these methods help us call out.flush().
*/
}
}

IO Other streams in the package

The next three are memory arrays :

* Byte array stream ByteArrayInputStream And ByteArrayOutputStream

* Character array stream CharArrayReader And CharArrayWriter

* Character stream StringReader And StringWriter

1、 Stream objects for manipulating byte arrays , In fact, they are the stream objects whose corresponding devices are memory . 2、 The closure of the stream is invalid , Because no system resources have been called . 3、 Operate the elements in the array according to the reading and writing idea of the stream .

* Sequence flow

SequenceInputStream —— Merging multiple streams 

Logical concatenation of multiple streams ( Merge into a stream , It's very convenient to operate , Because multiple sources become one source )

IO Summary of knowledge flow

Streams are used to process data . While processing data , Be sure to identify the data source and data destination first ( Data collection ). The data source can be a file 、 Keyboards or other streams . Data destinations can be files 、 Display or other streams . The stream is just helping the data transfer , And the transmitted data is processed , Like filtering 、 Conversion processing, etc .

* IO Flow system

Use points : Look at the top floor ( The generic function of the parent class ), Use the bottom layer ( Subclass concrete objects ).

Naming rules :

The suffix name of each subclass is the name of the parent class of the system to which it belongs , It's easy to tell which system you belong to . And each subclass prefix name is the functional embodiment of the subclass object .

master IO The main points and rules of flow system , It's much easier to design and find the corresponding class during development

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Familiar with memory]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121155638301v.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云