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 Flow class diagram structure :

Java IO Stream object

1. Input byte stream InputStream

Definition and structure description :

As you can see from the inheritance diagram of the input byte stream :

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 , And Piped
Related knowledge will be introduced separately later .

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). As shown in the figure below :

Example operation demonstration :

【 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. The corresponding diagram of input and output of byte stream

The blue one in the picture is the main corresponding part , The red part is the wrong part . The purple dotted line represents these streams, which should be used together . As you can see from the picture above Java IO The byte stream in is extremely symmetric . Philosophically speaking “ Existence and rationality ”, Now let's take a look at the asymmetric classes in these byte streams !

4. 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));
}
}
}

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

6. 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 .

7. The correspondence between input and output of character stream

8. 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 .

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

9.File class

File Class is an object that encapsulates files and folders in a file system , You can manipulate files and folders through the idea of objects . File Class to hold various metadata information about a file or directory , Include the file name 、 file length 、 Last modified 、 Is it readable? 、 Get the pathname of the current file , Determine whether the specified file exists 、 Get a list of files in the current directory , establish 、 Delete files and directories etc .

【 Case study 】 Create a file

import java.io.*;
class hello{
public static void main(String[] args) {
File f=new File("D:\\hello.txt");
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}

【 Case study 2】File Two constants of the class

import java.io.*;
class hello{
public static void main(String[] args) {
System.out.println(File.separator);
System.out.println(File.pathSeparator);
}
}

Let's say a few more words here : Some students may think that , I am directly in windows Next use \ Can't we split it up ? Of course you can . But in linux No, it's not \ 了 . therefore , To make our code cross platform , More robust , therefore , Let's all use these two constants , In fact, I can't write a few more lines .

【 Case study 3】File Constant rewriting case in class 1 Code for :

import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}

【 Case study 4】 Delete a file ( Or folders )

import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
if(f.exists()){
f.delete();
}else{
System.out.println(" file does not exist ");
} }
}

【 Case study 5】 Create a folder

/**
* Create a folder
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello";
File f=new File(fileName);
f.mkdir();
}
}

【 Case study 6】 List all files in the directory

/**
* Use list Lists all the files in the specified directory
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator;
File f=new File(fileName);
String[] str=f.list();
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}

Pay attention to list The return is String Array ,. And it's not a complete path , If you want to list the full path , Need to use listFiles. It's going to return zero File Array of .

【 Case study 7】 Lists all the files in the specified directory ( Including hidden files ):

/**
* Use listFiles Lists all the files in the specified directory
* listFiles The output is the full path
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator;
File f=new File(fileName);
File[] str=f.listFiles();
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}

【 Case study 8】 Determine whether a specified path is a directory

/**
* Use isDirectory Determine whether a specified path is a directory
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator;
File f=new File(fileName);
if(f.isDirectory()){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}

【 Case study 9】 Recursively searches the entire contents of the specified directory , Including files and folders

* List all the contents of the specified directory 
* */
import java.io.*;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator;
File f=new File(fileName);
print(f);
}
public static void print(File f){
if(f!=null){
if(f.isDirectory()){
File[] fileArray=f.listFiles();
if(fileArray!=null){
for (int i = 0; i

10.RandomAccessFile class

The object is not a member of the fluid system , It encapsulates the byte stream , It also encapsulates a buffer ( A character array ), Operate the data in the character array through the internal pointer . The object features :

This object can only operate on files , So constructors take two types of arguments :a. String file path ;b.File object .

This object can read the file , It can also write , Operation mode can be specified during object instantiation (r,rw)

Be careful : When the object is instantiated , If the file to be operated does not exist , Automatically created ; If the file exists , Write data does not specify location , Will write from the beginning , That is, to cover the original content . It can be used for multi thread download or multi thread write data to file at the same time .

【 Case study 】 Use RandomAccessFile write file

/**
* Use RandomAccessFile write file
* */
import java.io.*;
class hello{
public static void main(String[]args) throws IOException {
StringfileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
RandomAccessFile demo=newRandomAccessFile(f,"rw");
demo.writeBytes("asdsad");
demo.writeInt(12);
demo.writeBoolean(true);
demo.writeChar('A');
demo.writeFloat(1.21f);
demo.writeDouble(12.123);
demo.close();
}
}

Java IO Advanced concepts of flow

Coding problem

【 Case study 】 Get the local default encoding

/**
* Get the local default encoding
* */
publicclass CharSetDemo{
public static void main(String[] args){
System.out.println(" The system default code is :"+ System.getProperty("file.encoding"));
}
}

【 Case study 】 The generation of garbled code

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream; /**
* The generation of garbled code
* */
public class CharSetDemo2{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator + "hello.txt");
OutputStream out = new FileOutputStream(file);
byte[] bytes = " Hello ".getBytes("ISO8859-1");
out.write(bytes);
out.close();
}// The output is garbled , The system default code is GBK, And the code here is ISO8859-1
}

object serialization

Object serialization is a way to turn an object into a binary data stream .

If a class wants to be serialized , Just do it. It has to be done java.io.Serializable Interface . Although there are no methods in this interface , Just like before cloneable As the interface . After implementing this interface , It means that this class has the ability to be serialized . Let's implement a serializable class first :

【 Case study 】 Implement serializable classes

import java.io.*;
/**
* Implement serializable classes
* */
public class SerializableDemo implements Serializable{
public SerializableDemo(){ }
publicSerializableDemo(String name, int age){
this.name=name;
this.age=age;
}
@Override
public String toString(){
return " full name :"+name+" Age :"+age;
}
private String name;
private int age;
}

【 Case study 】 Serialize an object – ObjectOutputStream

import java.io.Serializable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* Implement serializable classes
* */
public class Person implements Serializable{
public Person(){
}
public Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public String toString(){
return " full name :" +name + " Age :" +age;
}
private String name;
private int age;
}
/**
* demonstration ObjectOutputStream
* */
public class ObjectOutputStreamDemo{
public static voidmain(String[] args) throws IOException{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(
file));
oos.writeObject(newPerson("rollen", 20));
oos.close();
}
}

【 Case study 】 Deserialization —ObjectInputStream

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream; /**
* ObjectInputStream demonstration
* */
public class ObjectInputStreamDemo{
public static voidmain(String[] args) throws Exception{
File file = new File("d:" +File.separator + "hello.txt");
ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
file));
Object obj =input.readObject();
input.close();
System.out.println(obj);
}
}

Be careful : By Serializable The properties of the object of the class declared by the interface will be serialized , But if you want to customize the serialized content , It needs to be realized Externalizable Interface .

When a class wants to use Externalizable When this interface , This class must have a parameterless constructor , If not , There will be an exception when constructing , This is because the nonparametric constructor will be called by default in the reverse sequence call .

Now let's demonstrate serialization and deserialization :

【 Case study 】 Use Externalizable To customize the serialization and deserialization operations

package IO;
import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream; /**
* Serialization and deserialization operations
* */
public class ExternalizableDemo{
public static voidmain(String[] args) throws Exception{
ser(); // serialize
dser(); // Reverse sequence words
} public static void ser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
file));
out.writeObject(newPerson("rollen", 20));
out.close();
} public static void dser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
file));
Object obj =input.readObject();
input.close();
System.out.println(obj);
}
} class Person implements Externalizable{
public Person(){ } public Person(String name,int age){
this.name = name;
this.age = age;
} @Override
public String toString(){
return " full name :" +name + " Age :" +age;
} // Copy this method , Properties or specific contents that can be saved as needed , Use... In serialization
@Override
public voidwriteExternal(ObjectOutput out) throws IOException{
out.writeObject(this.name);
out.writeInt(age);
} // Copy this method , Read content as needed When you're talking in reverse sequence, you need to
@Override
public voidreadExternal(ObjectInput in) throws IOException,
ClassNotFoundException{
this.name = (String)in.readObject();
this.age =in.readInt();
} private String name;
private int age;
}

Be careful :Serializable The operation implemented by the interface is actually to serialize all the attributes in an object , Of course, it can also be used. What we use is Externalizable Interface to realize the serialization of some properties , But this kind of operation is more troublesome ,

When we use Serializable When the interface implements the serialization operation , If an attribute of an object does not want to be serialized and saved , Then we can use transient Key words :

【 Case study 】 Use transient Keyword custom serialization and deserialization operations

package IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; /**
* Serialization and deserialization operations
* */
public class serDemo{
public static voidmain(String[] args) throws Exception{
ser(); // serialize
dser(); // Reverse sequence words
} public static void ser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
file));
out.writeObject(newPerson1("rollen", 20));
out.close();
} public static void dser()throws Exception{
File file = newFile("d:" + File.separator + "hello.txt");
ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
file));
Object obj =input.readObject();
input.close();
System.out.println(obj);
}
} class Person1 implements Serializable{
public Person1(){ } public Person1(Stringname, int age){
this.name = name;
this.age = age;
} @Override
public String toString(){
return " full name :" +name + " Age :" +age;
} // Note that there
private transient Stringname;
private int age;
}

【 Running results 】:

full name :null Age :20

【 Case study 】 Serialize a set of objects

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; /**
* Serialize a set of objects
* */
public class SerDemo1{
public static voidmain(String[] args) throws Exception{
Student[] stu = { newStudent("hello", 20), new Student("world", 30),
newStudent("rollen", 40) };
ser(stu);
Object[] obj = dser();
for(int i = 0; i

reference :

1、http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html

2、http://www.cnblogs.com/oubo/archive/2012/01/06/2394638.html

3、 Reprinted from the red and black League

java IO More related articles on Streaming

  1. 《Java Basic knowledge of 》Java IO Flow and explain in detail

    Java IO Concept 1. For data transmission between devices . 2. Java Encapsulate the function of operating data stream into IO In bag . 3. The data flow direction is divided into : Input and output streams , The operation object is the file . 4. The flow is divided according to the operation data : Byte stream ( Universal ) and ...

  2. Java IO Flow and explain in detail ( 6、 ... and )—— Converted flow

    A conversion stream is also a processing stream , It provides conversion between byte stream and character stream . stay Java IO Two conversion streams are provided in the stream :InputStreamReader and OutputStreamWriter, Both classes belong to the character stream . among I ...

  3. Java IO Flow and explain in detail ( 5、 ... and )—— Buffer flow

    Buffer flow is also called efficient flow , It's a kind of processing flow , That is, the flow acting on the flow . Its purpose is to speed up the speed of reading and writing data . The buffer itself doesn't have IO function , Just add buffer effect to other streams to improve efficiency . When the file or other target is read and written frequently or the operation efficiency is low , ...

  4. Java IO Flow and explain in detail ( Two )——File class

    In the last chapter, I briefly introduced Java IO Some characteristics of flow . That is, the input and output of the file , Since documents are indispensable from beginning to end , therefore Java IO The use of stream depends on File This class talks about . File Class description :File Classes are file and directory paths ...

  5. Java IO Flow and explain in detail ( One )—— Brief introduction

    Files are transmitted as streams in programs . So use Java To transfer files, you have to use Java IO flow . 1. The concept and function of flow flow : Represents any data source object that has the ability to produce data or the receiver object that has the ability to receive data <Thinkin ...

  6. Java io Flow detailed explanation 4

    Reprinted address :http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html Write it at the front : This article basically covers java IO The whole content of ,jav ...

  7. Java io Flow detailed explanation 2

    Original address https://www.cnblogs.com/xll1025/p/6418766.html One .IO Flow overview summary : IO Flow is simply Input and Output flow ,IO Stream is mainly used to deal with the relationship between devices ...

  8. Java IO Flow and explain in detail ( Four )—— Character stream Reader and Writer

    The previous chapter describes the use of byte streams , Mentioned that the byte stream is processing utf-8 The encoded Chinese may be garbled ( Other Chinese codes are also garbled ), therefore Java In view of this situation, a character stream is provided . But character streams can only handle characters , It can't be used to deal with . ...

  9. Java IO Flow and explain in detail ( 3、 ... and )—— Byte stream InputStream and OutPutStream

    We all know that in computers , No matter the text . picture . Audio or video , All the files are in binary ( byte ) In form ,IO Stream provides a series of streams for byte input and output , Collectively referred to as byte stream . Byte stream is the most commonly used stream in programs . stay JDK in , Provides two ...

Random recommendation

  1. delphi Read excel The two methods

    http://www.cnblogs.com/ywangzi/archive/2012/09/27/2705894.html The two methods , One is to use ADO Connect , The problem is Excel The content of the document should be regular , The second is to use OLE hit ...

  2. About LZO and LZOP

    LZO   Is a suitable real-time decompression . Compressed Library LZOP be based on LZO Library compression tool   PS: With the compression and decompression Library LZO, Can not directly operate the file compression and decompression , need LZOP   Download it directly google Well ~~~  

  3. ubuntu Hisense Hisense E920 usb Can't connect processing with adb The connection of

    solve lssub Failed to find Hisense Hisense USB Set up : choice Tianyi broadband connection As shown below : luogw@luogw-ThinkPad-Edge:~$ lsusb Bus 001 Device 002: ID ...

  4. maps.reg

    ^/(.*\.miaopai.com/stream/.*\.mp4\?.*) http://$1 ^/([[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{ ...

  5. tkinter brief introduction ( One )

    Tkinter( Also called Tk Interface ) yes Tk GUI toolkit standard Of Python Interface .Tk It's a lightweight cross platform gui (GUI) development tool . Tk and Tkinter Can run in most Of ...

  6. High availability Redis( 5、 ... and ): Slow inquiry of Swiss Army knife ,Pipeline And publish subscribe

    1. The slow query 1.1 The life cycle of slow queries Step one :client Through the Internet to Redis Send a command Step two : because Redis It's a single threaded application , You can put Redis Think of it as a queue ,client All the orders that are executed are waiting in line s ...

  7. yum Command to see which package a command is provided by

    [root@linux-node2 ~]$ yum whatprovides fuserLoaded plugins: fastestmirrorLoading mirror speeds from ...

  8. Ant Basic knowledge of 1

    1.Ant brief introduction Apache Ant It's about compiling software / test / Deployment and other steps are linked together to optimize a build tool , Commonly used in java Software development in the environment .Ant The default profile for is build.xml. Yes java Language support ...

  9. format Formatted string

    If you want to express such a sentence : Li Ming is twelve years old Output such a statement name = 'LiMing' age = 12 print( name + 'is' + age + 'years old') # Output L ...

  10. Spring Learning notes ( One ): Quick start

    Spring brief introduction :        Spring It's an open source framework , It consists of Rod Johnson establish . It is created to solve the complexity of enterprise application development .Spring Use basic JavaBean To finish before it could only be done by EJB End ...