Has been to IO I don't know , Turn around from somewhere else .

Look at the picture below :

The concept and function of flow

Study Java IO, It has to be mentioned that JavaIO flow .

Flow is a set of sequential , Set of bytes with start and end points , Is the general term or abstraction of data transmission . That is, the transmission of data between two devices is called streaming , The essence of stream is data transmission , According to the characteristics of data transmission, streams are abstracted into various kinds , Convenient and more intuitive data operation .

IO Classification of flows

According to different types of processing data, it can be divided into : Character stream and byte stream

According to the flow of data, it can be divided into : Input and output streams

Character stream and byte stream

The origin of character stream : Because of the difference in data coding , And with stream objects that operate efficiently on characters . The essence is based on byte stream reading , Went to check the designated code table .

The difference between byte stream and character stream :

(1) Different reading and writing units : Byte stream in bytes (8bit) In units of , The character stream is in characters , Map characters according to the code table , You can read more than one byte at a time .

(2) Different people to deal with : Byte streams can handle all types of data ( Such as images 、avi etc. ), And character stream can only handle data of character type .

(3) The byte stream itself will not use the buffer when operating , The direct operation is the file itself ; And the character stream will use buffer after operation , It's through buffers to manipulate files , We'll test that below .

Conclusion : Byte stream is preferred . First of all, all the files on the hard disk are transferred or saved in the form of bytes , Including pictures and so on . But characters are only formed in memory , So in development , Byte stream is widely used .

Input and output streams

The input stream can only be read , You can only write to the output stream , The program needs to use different streams according to the different characteristics of the data to be transmitted .

Java IO Stream object

1. Input byte stream InputStream

Definition and structure description :

InputStream Is the parent of all input byte streams , It's an abstract class .

ByteArrayInputStream、StringBufferInputStream、FileInputStream There are three basic media streams , They are from Byte Array 、StringBuffer、 And read data from local files .PipedInputStream Is to read data from a pipe shared with other threads .

ObjectInputStream And all FilterInputStream All subclasses of are decorative streams ( The protagonist of decorator mode ). intend FileInputStream Class can be implemented through a String Pathname creates an object ,FileInputStream(String name). and DataInputStream You have to decorate a class to return an object ,DataInputStream(InputStream in).

【 Case study 】 Read file contents

 /**
* Byte stream
* Read the contents of the document
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
InputStream in=new FileInputStream(f);
byte[] b=new byte[1024];
in.read(b);
in.close();
System.out.println(new String(b));
}
}

Be careful : In this example, due to b The length of the byte array is 1024, If the file is smaller , There will be a lot of padding . We can use in.read(b); To design a program , The following cases :

【 Case study 】 Read file contents

 /**
* Byte stream
* Read the contents of the document
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
InputStream in=new FileInputStream(f);
byte[] b=new byte[1024];
int len=in.read(b);
in.close();
System.out.println(" The reading length is :"+len);
System.out.println(new String(b,0,len));
}
}

Be careful : If you look at the example above, you can see that , We applied in advance for a space of a specified size , But sometimes the space may be too small , Sometimes it can be too big , We need the exact size , This saves space , So we can do that :

【 Case study 】 Read file contents

 /**
* Byte stream
* Read the contents of the document , Save a space
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
InputStream in=new FileInputStream(f);
byte[] b=new byte[(int)f.length()];
in.read(b);
System.out.println(" File length is :"+f.length());
in.close();
System.out.println(new String(b));
}
}

【 Case study 】 Read byte by byte

 /**
* Byte stream
* Read the contents of the document , Save a space
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
InputStream in=new FileInputStream(f);
byte[] b=new byte[(int)f.length()];
for (int i = 0; i < b.length; i++) {
b[i]=(byte)in.read();
}
in.close();
System.out.println(new String(b));
}
}

Be careful : The above examples are all about knowing the size of the file , And then it started , Sometimes we don't know how big the file is , In this case , We need to judge whether it's unique to the end of the file .

【 Case study 】 Byte stream read file

 /**
* Byte stream
* Reading documents
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
InputStream in=new FileInputStream(f);
byte[] b=new byte[1024];
int count =0;
int temp=0;
while((temp=in.read())!=(-1)){
b[count++]=(byte)temp;
}
in.close();
System.out.println(new String(b));
}
}

Be careful : When reading to the end of the file, it returns -1. Normally, it will not return -1 Of .

【 Case study 】DataInputStream class

 import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; public class DataOutputStreamDemo{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator +"hello.txt");
DataInputStream input = new DataInputStream(new FileInputStream(file));
char[] ch = new char[10];
int count = 0;
char temp;
while((temp = input.readChar()) != 'C'){
ch[count++] = temp;
}
System.out.println(ch);
}
}

【 Case study 】PushBackInputStream Backflow operation

 import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream; /**
* Backflow operation
* */
public class PushBackInputStreamDemo{
public static void main(String[] args) throwsIOException{
String str = "hello,rollenholt";
PushbackInputStream push = null;
ByteArrayInputStream bat = null;
bat = new ByteArrayInputStream(str.getBytes());
push = new PushbackInputStream(bat);
int temp = 0;
while((temp = push.read()) != -1){
if(temp == ','){
push.unread(temp);
temp = push.read();
System.out.print("( Back off " +(char) temp + ") ");
}else{
System.out.print((char) temp);
}
}
}
}

2. Output byte stream OutputStream

Definition and structure description :

IO The inheritance diagram of the output byte stream in is shown in the figure above , It can be seen that :

OutputStream Is the parent of all output byte streams , It's an abstract class .

ByteArrayOutputStream、FileOutputStream There are two basic media streams , They are to Byte Array 、 And write data to local files .PipedOutputStream Is to write data to a pipe shared with other threads ,

ObjectOutputStream And all FilterOutputStream All subclasses of are decorative streams . The specific examples are as follows InputStream Is the corresponding .

Example operation demonstration :

【 Case study 】 Write a string to a file

 /**
* Byte stream
* Write a string to a file
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
OutputStream out =new FileOutputStream(f);
String str="Hello World";
byte[] b=str.getBytes();
out.write(b);
out.close();
}
}

You can also write to a file byte by byte :

【 Case study 】 Write the file byte by byte

 /**
* Byte stream
* Write a string byte by byte to the file
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
OutputStream out =new FileOutputStream(f);
String str="Hello World!!";
byte[] b=str.getBytes();
for (int i = 0; i < b.length; i++) {
out.write(b[i]);
}
out.close();
}
}

【 Case study 】 Add new content to the file

 /**
* Byte stream
* Add new content to the file :
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
OutputStream out =new FileOutputStream(f,true);//true Indicates the append mode , Otherwise, it is covered
String str="Rollen";
//String str="\r\nRollen"; You can change lines
byte[] b=str.getBytes();
for (int i = 0; i < b.length; i++) {
out.write(b[i]);
}
out.close();
}
}

【 Case study 】 Copy file

 /**
* Copy of documents
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
if(args.length!=2){
System.out.println(" Wrong input of command line parameters , Please check ");
System.exit(1);
}
File file1=new File(args[0]);
File file2=new File(args[1]); if(!file1.exists()){
System.out.println(" The copied file does not exist ");
System.exit(1);
}
InputStream input=new FileInputStream(file1);
OutputStream output=new FileOutputStream(file2);
if((input!=null)&&(output!=null)){
int temp=0;
while((temp=input.read())!=(-1)){
output.write(temp);
}
}
input.close();
output.close();
}
}

【 Case study 】 Use the memory operation stream to convert an uppercase letter to a lowercase letter

 /**
* Use the memory operation stream to convert an uppercase letter to a lowercase letter
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String str="ROLLENHOLT";
ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream output=new ByteArrayOutputStream();
int temp=0;
while((temp=input.read())!=-1){
char ch=(char)temp;
output.write(Character.toLowerCase(ch));
}
String outStr=output.toString();
input.close();
output.close();
System.out.println(outStr);
}
}

【 Case study 】 Verify pipe flow : Interprocess communication

 /**
* Verify pipe flow
* */
import java.io.*; /**
* Message sending class
* */
class Send implements Runnable{
private PipedOutputStream out=null;
public Send() {
out=new PipedOutputStream();
}
public PipedOutputStream getOut(){
return this.out;
}
public void run(){
String message="hello , Rollen";
try{
out.write(message.getBytes());
}catch (Exception e) {
e.printStackTrace();
}try{
out.close();
}catch (Exception e) {
e.printStackTrace();
}
}
} /**
* Accept message class
* */
class Recive implements Runnable{
private PipedInputStream input=null;
public Recive(){
this.input=new PipedInputStream();
}
public PipedInputStream getInput(){
return this.input;
}
public void run(){
byte[] b=new byte[1000];
int len=0;
try{
len=this.input.read(b);
}catch (Exception e) {
e.printStackTrace();
}try{
input.close();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(" The accepted content is "+(new String(b,0,len)));
}
}
/**
* Test class
* */
class hello{
public static void main(String[] args) throws IOException {
Send send=new Send();
Recive recive=new Recive();
try{
// Pipe connection
send.getOut().connect(recive.getInput());
}catch (Exception e) {
e.printStackTrace();
}
new Thread(send).start();
new Thread(recive).start();
}
}

【 Case study 】DataOutputStream Class example

 import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataOutputStreamDemo{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator +"hello.txt");
char[] ch = { 'A', 'B', 'C' };
DataOutputStream out = null;
out = new DataOutputStream(new FileOutputStream(file));
for(char temp : ch){
out.writeChar(temp);
}
out.close();
}
}

【 Case study 】ZipOutputStream class

Have a look first ZipOutputStream Class inheritance

java.lang.Object

java.io.OutputStream

java.io.FilterOutputStream

java.util.zip.DeflaterOutputStream

java.util.zip.ZipOutputStream

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; public class ZipOutputStreamDemo1{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator +"hello.txt");
File zipFile = new File("d:" + File.separator +"hello.zip");
InputStream input = new FileInputStream(file);
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
// Set comments
zipOut.setComment("hello");
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
zipOut.close();
}
}

【 Case study 】ZipOutputStream Class compresses multiple files

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; /**
* Compress multiple files at once
* */
public class ZipOutputStreamDemo2{
public static void main(String[] args) throws IOException{
// The folder to be compressed
File file = new File("d:" + File.separator +"temp");
File zipFile = new File("d:" + File.separator + "zipFile.zip");
InputStream input = null;
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
zipFile));
zipOut.setComment("hello");
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i = 0; i < files.length; ++i){
input = newFileInputStream(files[i]);
zipOut.putNextEntry(newZipEntry(file.getName()
+ File.separator +files[i].getName()));
int temp = 0;
while((temp = input.read()) !=-1){
zipOut.write(temp);
}
input.close();
}
}
zipOut.close();
}
}

【 Case study 】ZipFile Class display

 import java.io.File;
import java.io.IOException;
import java.util.zip.ZipFile; /**
*ZipFile demonstration
* */
public class ZipFileDemo{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator +"hello.zip");
ZipFile zipFile = new ZipFile(file);
System.out.println(" The name of the compressed file is :" + zipFile.getName());
}
}

【 Case study 】 Unzip the file ( When there is only one file in the compressed file )

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; /**
* Unzip the file ( When there is only one file in the compressed file )
* */
public class ZipFileDemo2{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator +"hello.zip");
File outFile = new File("d:" + File.separator +"unZipFile.txt");
ZipFile zipFile = new ZipFile(file);
ZipEntry entry =zipFile.getEntry("hello.txt");
InputStream input = zipFile.getInputStream(entry);
OutputStream output = new FileOutputStream(outFile);
int temp = 0;
while((temp = input.read()) != -1){
output.write(temp);
}
input.close();
output.close();
}
}

【 Case study 】ZipInputStream Class decompresses a compressed file containing multiple files

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream; /**
* Decompression of a compressed file containing multiple files
* */
public class ZipFileDemo3{
public static void main(String[] args) throws IOException{
File file = new File("d:" +File.separator + "zipFile.zip");
File outFile = null;
ZipFile zipFile = new ZipFile(file);
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = null;
InputStream input = null;
OutputStream output = null;
while((entry = zipInput.getNextEntry()) != null){
System.out.println(" decompression " + entry.getName() + " file ");
outFile = new File("d:" + File.separator + entry.getName());
if(!outFile.getParentFile().exists()){
outFile.getParentFile().mkdir();
}
if(!outFile.exists()){
outFile.createNewFile();
}
input = zipFile.getInputStream(entry);
output = new FileOutputStream(outFile);
int temp = 0;
while((temp = input.read()) != -1){
output.write(temp);
}
input.close();
output.close();
}
}
}

3. Several special input stream class analysis

LineNumberInputStream

The main completion of reading data from the stream , You'll get the corresponding line number , As for when to branch 、 Where the branch is located is determined by the change of category , It's not that there's such a line number in the original . There is no corresponding section in the output section , We can build one of our own LineNumberOutputStream, There will be a baseline line number when initially written , In the future, a line number will be added to the next line every time a new line is encountered , It seems to be ok too . It seems to be more out of fashion .

PushbackInputStream

Its function is to look at the last byte , If you are not satisfied, put it in the buffer . Mainly used in compiler syntax 、 Part of lexical analysis . The output part of BufferedOutputStream Almost achieve similar functions .

StringBufferInputStream

Has been Deprecated, It should not appear in itself InputStream part , Mainly because String It should be in the range of character stream . It has been abandoned , Of course, the output part doesn't need it any more ! It is also allowed to exist just to keep the version downward compatible .

SequenceInputStream

It can be thought of as a tool class , Read two or more input streams as one input stream in turn . It's quite possible to start from IO Remove... From the bag , Not at all IO Package structure , But make it more “ pure ”―― chaste Decorator Pattern .

【 Case study 】 Merge two text files into another text file

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream; /**
* Merge two text files into another text file
* */
public class SequenceInputStreamDemo{
public static voidmain(String[] args) throws IOException{
File file1 = newFile("d:" + File.separator + "hello1.txt");
File file2 = newFile("d:" + File.separator + "hello2.txt");
File file3 = newFile("d:" + File.separator + "hello.txt");
InputStream input1 =new FileInputStream(file1);
InputStream input2 =new FileInputStream(file2);
OutputStream output =new FileOutputStream(file3);
// Combined flow
SequenceInputStreamsis = new SequenceInputStream(input1, input2);
int temp = 0;
while((temp =sis.read()) != -1){
output.write(temp);
}
input1.close();
input2.close();
output.close();
sis.close();
}
}

PrintStream

It can also be regarded as an auxiliary tool . It can mainly output to other streams , perhaps FileInputStream Write data , Its internal implementation is buffered . In essence, it is just a tool for the comprehensive use of other streams . You can also kick IO package !System.err and System.out Namely PrintStream Example !

【 Case study 】 Use PrintStream For the output

 /**
* Use PrintStream For the output
* */
import java.io.*; class hello {
public static void main(String[] args) throws IOException {
PrintStream print = new PrintStream(new FileOutputStream(newFile("d:"
+ File.separator +"hello.txt")));
print.println(true);
print.println("Rollen");
print.close();
}
}

【 Case study 】 Use PrintStream Format the output

 /**
* Use PrintStream For the output
* And format
* */
import java.io.*;
class hello {
public static void main(String[] args) throws IOException {
PrintStream print = new PrintStream(new FileOutputStream(newFile("d:"
+ File.separator +"hello.txt")));
String name="Rollen";
int age=20;
print.printf(" full name :%s. Age :%d.",name,age);
print.close();
}
}

【 Case study 】 Use OutputStream Output to the screen

 /**
* Use OutputStream Output to the screen
* */
import java.io.*;
class hello {
public static void main(String[] args) throws IOException {
OutputStream out=System.out;
try{
out.write("hello".getBytes());
}catch (Exception e) {
e.printStackTrace();
}
try{
out.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}

【 Case study 】 I / O redirection

 import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream; /**
* by System.out.println() Redirect output
* */
public class systemDemo{
public static void main(String[] args){
// Now it's going straight to the screen
System.out.println("hello");
File file = new File("d:" + File.separator +"hello.txt");
try{
System.setOut(new PrintStream(new FileOutputStream(file)));
}catch(FileNotFoundException e){
e.printStackTrace();
}
System.out.println(" These contents can only be seen in the file !");
}
}

【 Case study 】 Use System.err Redirect

 import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream; /**
*System.err The example of redirection also suggests that we can use this method to save error information
* */
public class systemErr{
public static void main(String[] args){
File file = new File("d:" + File.separator +"hello.txt");
System.err.println(" These are output on the console ");
try{
System.setErr(new PrintStream(new FileOutputStream(file)));
}catch(FileNotFoundException e){
e.printStackTrace();
}
System.err.println(" These can only be seen in the file !");
}
}

【 Case study 】System.in Redirect

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*System.in Redirect
* */
public class systemIn{
public static void main(String[] args){
File file = new File("d:" + File.separator +"hello.txt");
if(!file.exists()){
return;
}else{
try{
System.setIn(newFileInputStream(file));
}catch(FileNotFoundException e){
e.printStackTrace();
}
byte[] bytes = new byte[1024];
int len = 0;
try{
len = System.in.read(bytes);
}catch(IOException e){
e.printStackTrace();
}
System.out.println(" The content read in is :" + new String(bytes, 0, len));
}
}
}

4. Character input stream Reader

Define and explain :

As you can see from the inheritance diagram above :

Reader Is the parent of all input character streams , It's an abstract class .

CharReader、StringReader There are two basic media streams , They will, respectively Char Array 、String Read data from .PipedReader Is to read data from a pipe shared with other threads .

BufferedReader It's obviously a decorator , It and its subclasses are responsible for decorating other Reader object .

FilterReader Is the parent of all custom concrete decoration flows , Its subclass PushbackReader Yes Reader Objects to decorate , It will add a line number .

InputStreamReader It's a bridge between byte stream and character stream , It turns byte flow into character flow .FileReader It can be said that it is a way to achieve this function 、 Common utility classes , In its source code, it is obvious that FileInputStream Turn into Reader Methods . We can get some skills from this class .Reader The purpose and usage of each class in are basically the same as InputStream The use of classes in is consistent . There will be Reader And InputStream Correspondence of .

Example operation demonstration :

【 Case study 】 Read from file

 /**
* Character stream
* Read from the file
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
char[] ch=new char[100];
Reader read=new FileReader(f);
int count=read.read(ch);
read.close();
System.out.println(" The length read in is :"+count);
System.out.println(" The content is "+new String(ch,0,count));
}
}

Be careful : Of course, it's best to read in a loop , Because sometimes we don't know how big the file is .

【 Case study 】 Read content from a file in a circular fashion

 /**
* Character stream
* Read from the file
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
char[] ch=new char[100];
Reader read=new FileReader(f);
int temp=0;
int count=0;
while((temp=read.read())!=(-1)){
ch[count++]=(char)temp;
}
read.close();
System.out.println(" The content is "+new String(ch,0,count));
}
}

【 Case study 】BufferedReader The small example

Be careful :BufferedReader A buffer that can only accept character streams , Because each Chinese word needs to occupy two bytes , So we need to System.in This byte input flows into a character input stream , use :

BufferedReader  buf  =  new BufferedReader(new InputStreamReader(System.in));

Here is an example :

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; /**
* Use the buffer to read content from the keyboard
* */
public class BufferedReaderDemo{
public static void main(String[] args){
BufferedReader buf = new BufferedReader(
newInputStreamReader(System.in));
String str = null;
System.out.println(" Please enter the content ");
try{
str = buf.readLine();
}catch(IOException e){
e.printStackTrace();
}
System.out.println(" What you input is :" + str);
}
}

【 Case study 】Scanner Class instance

 import java.util.Scanner;
/**
*Scanner The small example , Read data from the keyboard
* */
public class ScannerDemo{
publicstatic void main(String[] args){
Scanner sca = new Scanner(System.in);
// Read an integer
int temp = sca.nextInt();
System.out.println(temp);
// Read floating point
float flo=sca.nextFloat();
System.out.println(flo);
// Read character
//... And so on , It's all too basic , It's not normal .
}
}

【 Case study 】Scanner Class reads from the file

 import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner; /**
*Scanner The small example , Read from a file
* */
public class ScannerDemo{
public static void main(String[] args){ File file = new File("d:" + File.separator +"hello.txt");
Scanner sca = null;
try{
sca = new Scanner(file);
}catch(FileNotFoundException e){
e.printStackTrace();
}
String str = sca.next();
System.out.println(" The content read from the file is :" + str);
}
}

5. Character output stream Writer

Define and explain :

As you can see from the diagram above :

Writer Is the parent of all output character streams , It's an abstract class .

CharArrayWriter、StringWriter There are two basic media streams , They are to Char Array 、String Middle write data .

PipedWriter Is to write data to a pipe shared with other threads ,

BufferedWriter It's a decorator for Writer Provide buffer function .

PrintWriter and PrintStream Very similar , The function and usage are very similar .

OutputStreamWriter yes OutputStream To Writer Bridge of transformation , Its subclass FileWriter In fact, it is a concrete class to realize this function ( Specifically, we can study one SourceCode). Function and use and OutputStream Very similar , There's a map of them in the back .

Example operation demonstration :

【 Case study 】 Write data to file

 /**
* Character stream
* Write data
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
Writer out =new FileWriter(f);
String str="hello";
out.write(str);
out.close();
}
}

Be careful : This example is no different from the previous one , It's just that you can just type in a string , You don't have to convert strings into byte arrays . When you want to ask for additional content in the file , You can use the statement above to out In which line of :

Writer out =new FileWriter(f,true);

such , When you run the program , You'll find that the contents of the file change to :hellohello If you want to wrap lines in a file , Need to use “\r\n” For example, will str Turn into String str="\r\nhello"; So the file is appended str The content will change lines .

6. Character stream and byte stream conversion

The characteristics of transition flow :

(1) It's a bridge between character stream and byte stream

(2) The read byte data can be converted into characters by specified encoding

(3) The read character data can be converted into bytes by specified encoding

When to use the transition flow ?

When there is a conversion action between bytes and characters ;

When the data of stream operation needs to be encoded or decoded .

Be careful : Byte stream to character stream only for text , If the operation is pictures and other information , From byte stream to character stream , Can cause data corruption .

The concrete object embodies :

InputStreamReader: Byte to character bridge

OutputStreamWriter: Character to byte bridge

These two stream objects are members of the character system , They're transformative , It's also a character stream , So when constructing, you need to pass in a byte stream object .

Examples of byte stream and character stream conversion :

【 Case study 】 Convert byte output stream to character output stream

 /**
* Convert byte output stream to character output stream
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName= "d:"+File.separator+"hello.txt";
File file=new File(fileName);
Writer out=new OutputStreamWriter(new FileOutputStream(file));
out.write("hello");
out.close();
}
}

【 Case study 】 Convert byte input stream to character input stream

 /**
* Change byte input into character input stream
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName= "d:"+File.separator+"hello.txt";
File file=new File(fileName);
Reader read=new InputStreamReader(new FileInputStream(file));
char[] b=new char[100];
int len=read.read(b);
System.out.println(new String(b,0,len));
read.close();
}
}

java Development of IO More articles on Streaming

  1. java Medium IO flow

    Java Medium IO flow I've been in touch before C# Medium IO flow , That is to say, one of the ways to solidify centralized data , So let's talk about it today java Medium IO flow . First , We learn IO A stream is a series of operations on a file or directory , So how to do it ...

  2. The first 55 section :Java In the middle of IO flow - Time api( Next )- On

    Java In the middle of IO flow ( Next )- On Date and time Date class :java.util.Date system time : long time = System.currentTimeMillis(); public class ...

  3. The first 54 section :Java In the middle of IO flow ( in )

    Java In the middle of IO flow ( in ) Delete directory // Jane book author : Da uncle niche import java.io.File; public class Demo{ public static void main(Stri ...

  4. The first 53 section :Java In the middle of IO flow ( On )

    Java In the middle of IO flow stay Java in , character string string Can be used to manipulate text data content , What is a string buffer ? It's just a container , It's also a string used to store a lot of data types , The appearance of basic data type wrapper class can be used to solve string and base ...

  5. Java Medium IO Stream summary

    Java Medium IO Stream summary 1. The inheritance of flow , And byte stream and character stream . 2. Node flow FileOutputStream and FileInputStream And processing streams BufferedInputStream and Buffe ...

  6. Java Medium IO A general introduction to

    because Java Medium IO There are many knowledge points in the flow , So I spent about 1 Weeks to put it together . But it's not the end of the story , I'll talk about it in byte stream and character stream . Then there are buffer streams in byte stream and character stream . End of story IO After streaming, I will ...

  7. Java Medium IO flow ,Input and Output Usage of , The difference between byte stream and character stream

    Java Medium IO flow : The input and output operations between the memory and the device become IO operation , That is to say IO flow . Data in memory is persisted to the device --------> Output (Output). hold The data on the hard disk is read into the memory , Such operation Become ...

  8. Java Medium IO flow ( 5、 ... and )

    Last one <Java Medium IO flow ( Four )> It was recorded Properties class , This class does not belong to IO flow , It belongs to the set framework . Let's move on IO Other streams in the stream One , Print stream PrintStream PrintStream ...

  9. Java Medium IO flow ( 6、 ... and )

    Last one <Java Medium IO flow ( 5、 ... and )> Put the print stream in the stream PrintStream,PrintWriter, Sequence flow SequenceInputStream And combined with the previous record of knowledge points to complete the file cutting and file ...

Random recommendation

  1. 【Prince2 What is it? 】PRINCE2 Certified Prince2 The six elements of measuring performance

      The previous article has explained to you from the system PRINCE2 and PMP The difference of , Let's go on to the second lecture ,PRINCE2 What are the elements of performance measurement mentioned in ? First of all , cost : That is, the project must be affordable second , Time : I.e. project ...

  2. Request Analysis of random code principle of receiving parameters : The example analysis

    Through the first two articles <Request Receiving parameter random code principle analysis 1 : The principle of server decoding > and <Request Analysis of random code principle of receiving parameters 2 : Browser side coding principle >, Understand the principle of server and browser encoding and decoding , continue with ...

  3. Study Coding-iOS Open source project log ( Four )

    Hello, Hello everyone , I haven't written a blog for a long time , Let's study it again today Coding Source code , have not seen for a long time . front said : As a junior programmer , I want to improve my level , One of the effective ways to learn is to learn other people's good projects . At the beginning of this article, I will update my understanding of git ...

  4. h5 Characteristics

    About HTML Summary of interview questions H5   One .H5 What's new , What elements were removed ? How to deal with it h5 Browser compatibility issues with new tags , How to distinguish between html and html5 1. html5 No, it's not SGL( Universal markup language ) A subset of , And the bag ...

  5. mysql database myisam Data storage engine Table corruption due to index and data Repair of And inspection

    One .mysqlcheck Check and repair the table 1. Check mysqlisam The state of the storage engine table #mysqlcheck -uuser -ppassword database  table  -c  # Checklist ...

  6. selenium+python note 10

    #!/usr/bin/env python # -*- coding: utf-8 -*- """ Let's add more test scenarios , such as : Delete mail , Find mail , Send email, etc &qu ...

  7. Backup Sqlite DB To XML file :

    Reprint please indicate the source :http://blog.csdn.net/krislight Project encountered backup and restore App The need for data , Need to put DB Back up the data to a XML In file , Then save to SD obstruct , Restore directly from XML file ...

  8. UESTC_ Minimum cost 2015 UESTC Training for Dynamic Programming&lt;Problem D&gt;

    D - Minimum cost Time Limit: 30000/10000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submi ...

  9. 115 ,JavaScript,DOM Operation form

    JavaScript,DOM Operation form Learning points : 1. Operation form DOM In operation generation HTML On , It's more concise . however , Because browsers always have compatibility and pitfalls , The final operation is not so simple and convenient . This chapter focuses on DO ...

  10. Set up select The height of the label

    When you can't give select When the label is set high , Give him a background color , You can set up .