【 Case study 1】 Create a new file

1
2
3
4
5
6
7
8
9
10
11
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();
         }
     }
}

【 Running results 】:

After the program runs , stay d There will be a name under the disk hello.txt The file of .

【 Case study 2】File Two properties of class Constant

1
2
3
4
5
6
7
import  java.io.*;
class  hello{
     public  static  void  main(String[] args) {
         System.out.println(File.separator);
         System.out.println(File.pathSeparator);
     }
}

【 Running results 】:

\

;

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 . ha-ha 、

Now we use File Class to rewrite the above code :

1
2
3
4
5
6
7
8
9
10
11
12
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();
         }
     }
}

You see , Not much more , ha-ha . So it is recommended to use File Constant in class .

Delete a file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
  * Delete a file
  * */
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 " );
         }
         
     }
}

Create a folder

1
2
3
4
5
6
7
8
9
10
11
/**
  * 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();
     }
}

【 Running results 】:

D There's one more on the plate hello Folder

Lists all the files in the specified directory ( Include Hidden files ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
  * 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]);
         }
     }
}

【 Running results 】:

$RECYCLE.BIN

360Downloads

360Rec

360SoftMove

Config.Msi

da

Downloads

DriversBackup

eclipse

java web Integrated development and project practice

Lenovo

MSOCache

Program

Program Files

python

RECYGLER.{8F92DA15-A229-A4D5-B5CE-5280C8B89C19}

System Volume Information

Tomcat6

var

vod_cache_data

New folder

( Your running result should be different from this one , ha-ha )

But use 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. He returned to File Array of

Lists all the files in the specified directory ( Including hidden files ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
  * 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]);
         }
     }
}

【 Running results 】:

D:\$RECYCLE.BIN

D:\360

D:\360Downloads

D:\360Rec

D:\360SoftMove

D:\Config.Msi

D:\da

D:\Downloads

D:\DriversBackup

D:\eclipse

D:\java web Integrated development and project practice

D:\Lenovo

D:\MSOCache

D:\Program

D:\Program Files

D:\python

D:\RECYGLER.{8F92DA15-A229-A4D5-B5CE-5280C8B89C19}

D:\System Volume Information

D:\Tomcat6

D:\var

D:\vod_cache_data

D:\ New folder

By comparison, you can specify , Use listFiles It is more convenient 、

 

Determine whether a specified path is a directory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
  * 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" );
         }
     }
}

【 Running results 】:YES

 

Search the entire contents of the specified directory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
  * 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 < fileArray.length; i++) {
                         // Recursively call
                         print(fileArray[i]);
                     }
                 }
             }
             else {
                 System.out.println(f);
             }
         }
     }
}

【 Running results 】:

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\framepages\web4welcome_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\help_005fhome_jsp.class

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\help_005fhome_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\home_jsp.class

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\home_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\index_jsp.class

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\index_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\login_jsp.class

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\login_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\modify_005fuser_005finfo_jsp.class

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\modify_005fuser_005finfo_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\register_005fnotify_jsp.class

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\register_005fnotify_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\sign_005fup_jsp.class

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\sign_005fup_jsp.java

D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\transit_jsp.class

……

【 Use RandomAccessFile write file 】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
  * Use RandomAccessFile write 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);
         RandomAccessFile demo= new  RandomAccessFile(f, "rw" );
         demo.writeBytes( "asdsad" );
         demo.writeInt( 12 );
         demo.writeBoolean( true );
         demo.writeChar( 'A' );
         demo.writeFloat( 1 .21f);
         demo.writeDouble( 12.123 );
         demo.close();  
     }
}

If you turn it on at this point hello.txt If you look at it , You'll find it's garbled .

 

Byte stream

【 Write a string to a file 】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
  * 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 " ;
         byte [] b=str.getBytes();
         out.write(b);
         out.close();
     }
}

see hello.txt Will see “ Hello ”

Of course, you can write one byte at a time .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
  * 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 " ;
         byte [] b=str.getBytes();
         for  ( int  i =
0 ; i < b.length; i++) {
             out.write(b[i]);
         }
         out.close();
     }
}

The results are :“ Hello ”

Add new content to the file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
  * 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 );
         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();
     }
}

【 Running results 】:

Hello Rollen

【 Read file contents 】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
  * 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));
     }
}

【 Running results 】

Hello Rollen

Rollen_

But this example reads out a lot of spaces , We can use in.read(b); To design a program . as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
  * 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));
     }
}

【 Running results 】:

Hello Rollen

Rollen

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 this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
  * 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));
     }
}

Hello Rollen

Rollen

Change the above example to read one by one :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
  * 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));
     }
}

The output is the same as above .

Careful readers may find this , 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 .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
  * 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));
     }
}

【 Running results 】

Hello Rollen

Rollen_

As a reminder , It returns when it reaches the end of the file -1. Normally, it will not return -1 Of

Character stream

【 Write data to file 】

Now we use character stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
  * 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();
     }
}

When you open hello.txt When , Will see hello

In fact, this example is no different from the previous ones , 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 .

Read from a file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
  * 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));
     }
}

【 Running results 】:

The content is hellohello

hello

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
  * 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));
     }
}

Running results :

The content is hellohello

hello

About the difference between byte stream and character stream

In fact, the byte stream itself will not use the buffer when operating , The direct operation is the file itself , But the character stream is operating   When the next buffer will be used , The file is manipulated through a buffer .

The reader can try to comment out the code of closing the file in the last line of the program of byte stream and character stream above , Then run the program and see . You'll find that with byte streams , Content already exists in the file , But when using character stream , There is still no content in the file , At this time, the buffer will be refreshed .

Is it better to use byte stream or character stream ?

The answer is byte stream . 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 .

Copy of documents

Actually DOS There is a file copy function , So let's say we want to d Under the plate hello.txt File copy to d Under the plate rollen.txt In file , Then we can use the following command :

copy d:\hello.txt d:\rollen.txt

After running, you will be in d I can see hello.txt., And the contents of the two files are the same ,( This is bullshit )

Now let's use the program to copy the file .

The basic idea is to read content from a file , Write to another file while reading , It's that simple .、

First write the following code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
  * 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();
     }
}

And then under the command line

javac hello.java

java hello d:\hello.txt d:\rollen.txt

Now you will be in d Disk see rollen.txt 了 ,

OutputStreramWriter  and InputStreamReader class

Whole IO Class includes not only byte stream and character stream, but also byte and character conversion stream .

OutputStreramWriter Convert the output character stream to byte stream

InputStreamReader Convert the input byte stream to character stream

But no matter how it works , Finally, they are all saved in the form of bytes in the file .

Convert byte output stream to character output stream

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
  * 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();
     }
}

Running results : The content of the document is :hello

Change byte input into character input stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
  * 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();
     }
}

【 Running results 】:hello

The output and input listed above are all in the form of files , Now we use content as our output and input destination , Use memory operation flow

ByteArrayInputStream  Mainly write the content into the content

ByteArrayOutputStream   Mainly output the content from memory

Use the memory operation stream to convert an uppercase letter to a lowercase letter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
  * 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);
     }
}

【 Running results 】:

rollenholt

Content operation flow is generally used to generate some temporary information , This can avoid the trouble of deletion .

Pipe flow

Pipeline flow can communicate between two threads .

PipedOutputStream  Pipeline output flow

PipedInputStream  Pipeline input flow

Verify pipe flow
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
  * 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();
     }
}

【 Running results 】:

The accepted content is  hello , Rollen

Print stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
  * Use PrintStream For the output
  * */
import  java.io.*;
 
class  hello {
     public  static  void  main(String[] args)
throws  IOException {
         PrintStream print = new  PrintStream( new  FileOutputStream( new  File( "d:"
                 + File.separator + "hello.txt" )));
         print.println( true );
         print.println( "Rollen" );
         print.close();
     }
}

【 Running results 】:

true

Rollen

Of course, you can also format the output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
  * 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( new  File( "d:"
                 + File.separator + "hello.txt" )));
         String name= "Rollen" ;
         int  age= 20 ;
         print.printf( " full name :%s. Age :%d." ,name,age);
         print.close();
     }
}

【 Running results 】:

full name :Rollen.  Age :20.

Use OutputStream Output to the screen

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
  * 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();
         }
     }
}

【 Running results 】:

hello

I / O redirection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 !" );
     }
}

【 Running results 】:

eclipse The output of the console is hello. And then when we look at d Under the plate hello.txt When you file , You'll see it in there : These contents can only be seen in the file !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import  java.io.File;
import  java.io.FileNotFoundException;
import  java.io.FileOutputStream;
import  java.io.PrintStream;
 
/**
  * System.err Redirect This example 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 !" );
     }
}

【 Running results 】:

Will you be in eclipse You can see the red output on the console :“ These are output on the console ”, And then in d Under the plate hello.txt Will see in the : These can only be seen in the file !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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( new  FileInputStream(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));
         }
     }
}

【 Running results 】:

The premise is my d Under the plate hello.txt The content of is :“ The contents of these documents !”, And then run the program , The output result is : The content read in is : The contents of these documents !

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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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(
                 new  InputStreamReader(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);
     }
}

Running results :

Please enter the content

dasdas

What you input is :dasdas

Scanner class

In fact, we usually use Scanner Class for data input , Let's give you a Scanner An example of

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import  java.util.Scanner;
 
/**
  * Scanner The small example , Read data from the keyboard
  * */
public  class  ScannerDemo{
     public  static  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 .
     }
}

Actually Scanner Can accept any input stream

Here's a use Scanner Class reads from the file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
     }
}

【 Running results 】:

The content read from the file is : The contents of these documents !

Data operation flow DataOutputStream、DataInputStream class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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();
     }
}

A B C

Now, based on the above example , Use DataInputStream Read out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
     }
}

【 Running results 】:

AB

Combined flow  SequenceInputStream

SequenceInputStream Mainly used to put 2 The streams merge together , For example, two txt The content in is merged into another txt. Here is an example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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  void  main(String[] args)
throws  IOException{
         File file1 = new  File( "d:"  + File.separator +
"hello1.txt" );
         File file2 = new  File( "d:"  + File.separator +
"hello2.txt" );
         File file3 = new  File( "d:"  + File.separator +
"hello.txt" );
         InputStream input1 = new  FileInputStream(file1);
         InputStream input2 = new  FileInputStream(file2);
         OutputStream output = new  FileOutputStream(file3);
         // Combined flow
         SequenceInputStream sis = new  SequenceInputStream(input1, input2);
         int  temp =
0 ;
         while ((temp = sis.read()) != - 1 ){
             output.write(temp);
         }
         input1.close();
         input2.close();
         output.close();
         sis.close();
     }
}

【 Running results 】

The result will be hello.txt The file contains hello1.txt and hello2.txt Contents of the file .

File compression  ZipOutputStream class

Let's take an example of compressing a single file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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();
     }
}

【 Running results 】

Before running the results , I created a hello.txt The file of , The original size 56 Bytes , But compression produces hello.zip after , It turns into 175 Bytes , It's a little confusing .

But the result must be right , I'm just asking a question .

The above example tests the compression of a single file , Let's take a look at how to compress multiple files .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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 = new  FileInputStream(files[i]);
                 zipOut.putNextEntry( new  ZipEntry(file.getName()
                         + File.separator + files[i].getName()));
                 int  temp =
0 ;
                 while ((temp = input.read()) != - 1 ){
                     zipOut.write(temp);
                 }
                 input.close();
             }
         }
         zipOut.close();
     }
}

【 Running results 】

Let's look at the files to be compressed first :

Let's take a look at the compressed :

It naturally occurred to you that , Since it can compress , Nature can decompress , Before we talk about decompression , We'll use a ZipFile class , Let's give an example first .java Every compressed file in can be used ZipFile To express

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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());
     }
}

【 Running results 】:

The name of the compressed file is :d:\hello.zip

Now it's time for us to see how to add compressed files , Same as before , Let's unzip a single compressed file first ( That is, there is only one file in the compressed file ), Let's use the compressed file generated in the previous example hello.zip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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();
     }
}

【 Running results 】:

Before decompression :

This compressed file is still 175 byte

After decompression, it produces :

Back to the 56 byte , It means depressed .

Now let's decompress a compressed file containing multiple files

ZipInputStream class

When we need to decompress multiple files ,ZipEntry Can't use , If you want to work with more complex compressed files , We have to use ZipInputStream class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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();
         }
     }
}

【 Running results 】:

Unzipped files :

Decompress and then D The next one will appear temp Folder , What's in it :

PushBackInputStream Backflow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import  java.io.ByteArrayInputStream;
import  java.io.IOException;
import  java.io.PushbackInputStream;
 
/**
  * Backflow operation
  * */
public  class  PushBackInputStreamDemo{
     public  static  void  main(String[] args)
throws  IOException{
         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);
             }
         }
     }
}

【 Running results 】:

hello( Back off ,) rollenholt

1
2
3
4
5
6
7
8
/**
  * Get the local default encoding
  * */
public  class  CharSetDemo{
     public  static  void  main(String[] args){
         System.out.println( " The system default code is :"  + System.getProperty( "file.encoding" ));
     }
}

【 Running results 】:

The system default code is :GBK

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

【 Running results 】:

??

In general, there is garbled code , It's all due to inconsistent coding .

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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import  java.io.*;
/**
  * Implement serializable classes
  * */
public  class  SerializableDemo
implements  Serializable{
     public  SerializableDemo(){
         
     }
     public  SerializableDemo(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;
}

This class has the ability to implement serialization ,

Before continuing to serialize , Let's start with ObjectInputStream and ObjectOutputStream These two classes

Give one first ObjectOutputStream An example of :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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  void  main(String[] args)
throws  IOException{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectOutputStream oos = new  ObjectOutputStream( new  FileOutputStream(
                 file));
         oos.writeObject( new  Person( "rollen" ,
20 ));
         oos.close();
     }
}

【 Running results 】:

When we look at the resulting hello.txt When , What I saw was a mess , ha-ha . Because it's binary .

Although we can't look at the contents directly , But we can use ObjectInputStream Class view :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import  java.io.File;
import  java.io.FileInputStream;
import  java.io.ObjectInputStream;
 
/**
  * ObjectInputStream demonstration
  * */
public  class  ObjectInputStreamDemo{
     public  static  void  main(String[] args)
throws  Exception{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectInputStream input = new  ObjectInputStream( new  FileInputStream(
                 file));
         Object obj = input.readObject();
         input.close();
         System.out.println(obj);
     }
}

【 Running results 】

What on earth is serializing ?

Only properties are serialized .

Externalizable Interface

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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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  void  main(String[] args)
throws  Exception{
         ser(); // serialize
         dser(); // Reverse sequence words
     }
 
     public  static  void  ser()
throws  Exception{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectOutputStream out = new  ObjectOutputStream( new  FileOutputStream(
                 file));
         out.writeObject( new  Person( "rollen" ,
20 ));
         out.close();
     }
 
     public  static  void  dser()
throws  Exception{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectInputStream input = 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  void  writeExternal(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  void  readExternal(ObjectInput in)
throws  IOException,
             ClassNotFoundException{
         this .name = (String) in.readObject();
         this .age = in.readInt();
     }
 
     private  String name;
     private  int  age;
}

【 Running results 】:

In this case , We've preserved all the attributes ,

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 :

Here's an example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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  void  main(String[] args)
throws  Exception{
         ser(); // serialize
         dser(); // Reverse sequence words
     }
 
     public  static  void  ser()
throws  Exception{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectOutputStream out = new  ObjectOutputStream( new  FileOutputStream(
                 file));
         out.writeObject( new  Person1( "rollen" ,
20 ));
         out.close();
     }
 
     public  static  void  dser()
throws  Exception{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectInputStream input = new  ObjectInputStream( new  FileInputStream(
                 file));
         Object obj = input.readObject();
         input.close();
         System.out.println(obj);
     }
}
 
class  Person1
implements  Serializable{
     public  Person1(){
 
     }
 
     public  Person1(String name,
int  age){
         this .name = name;
         this .age = age;
     }
 
     @Override
     public  String toString(){
         return  " full name :"  + name +
"  Age :"  + age;
     }
 
     // Note that there
     private  transient  String name;
     private  int  age;
}

【 Running results 】:

Finally, let's give an example of serializing a group of objects :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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  void  main(String[] args)
throws  Exception{
         Student[] stu = { new  Student( "hello" ,
20 ), new  Student( "world" ,
30 ),
                 new  Student( "rollen" ,
40 ) };
         ser(stu);
         Object[] obj = dser();
         for ( int  i =
0 ; i < obj.length; ++i){
             Student s = (Student) obj[i];
             System.out.println(s);
         }
     }
 
     // serialize
     public  static  void  ser(Object[] obj)
throws  Exception{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectOutputStream out = new  ObjectOutputStream( new  FileOutputStream(
                 file));
         out.writeObject(obj);
         out.close();
     }
 
     // Deserialization
     public  static  Object[] dser()
throws  Exception{
         File file = new  File( "d:"  + File.separator +
"hello.txt" );
         ObjectInputStream input = new  ObjectInputStream( new  FileInputStream(
                 file));
         Object[] obj = (Object[]) input.readObject();
         input.close();
         return  obj;
     }
}
 
class  Student
implements  Serializable{
     public  Student(){
 
     }
 
     public  Student(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;
}

【 Running results 】:

JAVA IO More related articles in detail

  1. Java IO Detailed explanation

    Java IO Detailed explanation Beginners java, I can't understand it all the time java Inside io Relationship , I found a lot of them on the Internet, most of them gave a cursory description of the structure diagram, but I didn't understand them very well . And it's not integrated into java7 The latest technology , So I'll sort it out for myself , If you are wrong, please correct me , ...

  2. JAVA IO Detailed explanation 2

    Java Stream is divided into character stream and byte stream in processing . The unit of character stream processing is 2 Bytes of  Unicode  character , Operate the characters separately . Character array or string , And the byte stream processing unit is 1 Bytes , Manipulating bytes and byte arrays . Java For internal use U ...

  3. Java IO Detailed explanation ( turn )

    IO yes Java And many programming languages are very important , At the same time, many program bottlenecks and time-consuming operations are also in IO This piece of . One . brief introduction IO There are many problems in operation , Huge amount of information , Network environment and so on , because IO Not just local files . Directory operation , Sometimes it's about two ...

  4. Java IO Detailed explanation ( One )------ Byte I / O stream

    File Class :http://www.cnblogs.com/ysocean/p/6851878.html Java IO Introduction to the classification of flow :http://www.cnblogs.com/ysocea ...

  5. Java IO Detailed explanation ( Two )------ Classification of flows

    One . According to the flow direction, it can be divided into input flow and output flow : Note that the input and output streams are relative to the program . Output : Put the program ( Memory ) Output the contents of to disk . CD and other storage devices       Input : Read external data ( disk . Data from storage devices such as optical disks ) To the program ( Inside ...

  6. Java IO Detailed explanation ( 6、 ... and )------ Serialization and deserialization ( Object flow )

    File Class :http://www.cnblogs.com/ysocean/p/6851878.html Java IO Introduction to the classification of flow :http://www.cnblogs.com/ysocea ...

  7. Java IO Detailed explanation ( 5、 ... and )------ Packaging flow

    File Class :http://www.cnblogs.com/ysocean/p/6851878.html Java IO Introduction to the classification of flow :http://www.cnblogs.com/ysocea ...

  8. Java IO Detailed explanation ( 6、 ... and )------ Random access to file streams

    File Class :http://www.cnblogs.com/ysocean/p/6851878.html Java IO Introduction to the classification of flow :http://www.cnblogs.com/ysocea ...

  9. Java IO Detailed explanation ( Four )------ Character input output stream

    File Class :http://www.cnblogs.com/ysocean/p/6851878.html Java IO Introduction to the classification of flow :http://www.cnblogs.com/ysocea ...

Random recommendation

  1. Spring Timing task configuration of ( turn )

    spring The timing task configuration of is divided into three steps : 1. Define the task  2. Task execution policy configuration  3. Start the task 1. Define the task  <!-- Methods to be executed regularly --> <bean id="testTas ...

  2. error: failed to initialize alpm library

    The problem is archlinux above [[email protected] pacman]# pacman -Syuerror: failed to initialize alpm library(database ...

  3. MySQL Database to get the initial function of Chinese pinyin

    Requirements introduction : A recent project , Want to achieve the display effect as shown in the figure below . Obviously , If we can get the first letter of Pinyin of the corresponding Chinese phrase, it can be realized , If it's a fixed number of Chinese characters , Just spell it artificially , However, there are many functions in the project that need this effect , also ...

  4. Cookie Summary of knowledge points

    What's the problem ? What are the technologies ? How to solve ? 1. Cookie 1) A mechanism to complete the call back tracking : It is saved on the client side Http Solution of state information 2)Cookie It's in the browser WEB When a resource of the server , from WEB The server ...

  5. ruby operation mongo DB

    web In automation , Verify the operation log function ( Operation log exists mongoDB in ). In order to avoid the log generated by the previous operation affecting the result verification , We need to clear all previous operation logs first . require 'mongo' host = '1 ...

  6. cygwin vi Editor left and right up and down key and delete key garbled error

    install cygwin Then use one of the vi Editor found up and down around the key and delete key garbled , Search the Chinese help program , No solution , Finally, I searched English websites , Found a solution . The reference link is as follows :http://superuser.com/que ...

  7. EXT obtain gird Each value

    var cellclick = function (item, td, cellIndex, record, tr, rowIndex, e) { //[ListenerArgument(0, &qu ...

  8. Win10 15063 The reason and solution of not saving history record in running

    http://www.ampc8.com/thread-23421-1-1.html stay Win10 1703 You may find that when you start running , Open it again and there's no history , The normal way is the desktop - Right click - Individualization - ...

  9. tencent QQ Business model of

    I've heard a lot about Tencent recently QQ Reports of , And then I thought I was QQ Some of the problems encountered on , In a flash, I feel all the thoughts coming out of my brain . I used to think QQ It's a great platform , We can go through QQ Talk to your family, friends and loved ones , Sometimes it can be in your own ...

  10. echarts The map doesn't display properly

    echarts2 Built in maps , and echarts3 No built-in map , You need to download and import . When I first came into contact with maps , Use dreamweaver To build the page , The encoding used is not UTF-8 The code is copied according to the official ( I use ...