Because arrays, variables, etc. store data only temporarily and will disappear after the program ends, so there is I/O, which can save files to local disk files.
Article directory
- Basic concepts of input and output streams
- File class
- file input and output stream
- Buffered input and output streams
- data input and output stream
- Zip compresses input and output streams
1. Basic concept of input and output stream
Stream:A stream is a set of ordered data sequences, which can be divided into input stream and output stream according to the type of operation
The InputStream class is the parent class of all byte input streams, and similarly, the Reader class is the parent class of all character input streams, and their methods are similar.
Common method:
- The read() method reads the next byte of data from the input stream, and returns an int value, if not, returns -1 (meaning that it returns the total number of bytes in the input stream)
- read(byte[]b), read a certain length of bytes from the input stream, and return an integer.
- mark(int readlimit) method, make a mark at the current position of the input stream
- The readlimit parameter is to inform the input stream of the number of bytes that are allowed to be read when the mark is invalid. The reset() method returns the input pointer to the current mark.
- skip(long n), skip n bytes on the input stream and return the actual number of bytes skipped
- markSupported(), returns true if the current stream supports the mark or reset method
- close() closes the input stream and releases resources associated with it
The OutputStream class and the Writer class correspond to the above two input classes, one is bytes and the other is characters. Nothing but output streams.
Common method:
- write(int b), writes the specified byte to this output stream
- write(byte[] b), write b bytes from the byte array to this output stream
- write(byte[] b, int off, int len), write the len bytes of the byte array starting from offset off to the output stream
- flush(), completely complete the input and clear the buffer
- close, close the output stream
2.File class
The File class is the class that operates on files
There are many ways to create files,
- File file=new File(“The path and file name of the file to be created (if there is no path, it will default to the project folder)”)
- File file=new File(“The path of the file to be created (if there is no path, it will be in the project folder by default), file name”)
Method | Return Value | Explanation |
---|---|---|
getName() | String | Get file name |
canRead() | boolean | Is the file readable? |
canWrite() | boolean | Is the file writable |
exits() | boolean | Whether the file exists |
length() | iong | The length of the file in bytes |
getAbsolutePath() | String | The absolute path of the file |
getParent() | String | The parent path of the file (that is, there is no file name path) |
isFile() | boolean | Whether the file exists |
isDirectory() | boolean | Whether the file is a directory |
isHidden() | boolean | Whether the file is a hidden file |
lastModified() | long | Get the last modified time of the file |
Example:
Code;
package com.cn; import java.io.File; public class Dom{ public static void main(String[]args){ File file=new File("E:/","word.txt"); if (file. exists()) { file.delete(); System.out.println("The file has been deleted"); } else { try { file. createNewFile(); System.out.println("The file has been created"); System.out.println("The path of the file: " + file.getAbsolutePath()); System.out.println("Parent path of the file: " + file.getParent()); }catch (Exception e){ e.printStackTrace(); } } } }
3. File input and output stream
There are four main types of file input and output:
- FileInputStream (inherited from InputStream)
- FileOutputStream (inherited from OutputStream)
- FileReader (inherited from Reader)
- FileWriter (inherited from Writer)
The method is basically mentioned above, because the inherited methods are basically the same.
Example:
package com.cn; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; public class Dom{ public static void main(String[]args) throws Exception{ //Create file object File file=new File("E:/","word.txt"); //Check if the file exists if (file. exists()) { file.delete(); System.out.println("The file has been deleted");//Delete if it exists } else { //Create the file if it does not exist file. createNewFile(); System.out.println("The file has been created"); System.out.println("The path of the file: " + file.getAbsolutePath()); System.out.println("Parent path of the file: " + file.getParent()); //Create a FileOutputStream class object FileOutputStream fileOutputStream=new FileOutputStream(file); byte b[]="Hello, world".getBytes(StandardCharsets.UTF_8);//Create an array fileOutputStream.write(b);//write fileOutputStream.close();//Close //Create a FileInputStream object FileInputStream fileInputStream=new FileInputStream(file); byte b1[]=new byte[1024]; int len=fileInputStream. read(b1); System.out.println("The text file is; " + new String(b1,0,len)); fileInputStream. close(); } } }
Result:
file created
The path of the file: E:\word.txt
Parent path of the file: E:\
The text file is; hello world
For an explanation of the getBytes method, please click
4. Input and output stream with cache
Caching is the performance optimization of I/O
There are also four:
- BufferedInputStream (inherited from InputStream)
- BufferedOutputStream (inherited from OutputStream)
- BufferedReader (inherited from Reader)
- BufferedWriter (inherited from Writer)
BufferedInputStream and BufferedOutputStream both have two similar construction methods:
1. BufferedInputStream (InputStream in)
2. BufferedInputStream (InputStream in, int size)
The first is to create a buffer stream with 32 bytes, and the second is a custom buffer. BufferedOutputStream is similar.
Common methods of BufferedReader:
read(), read a single character
readLine(), reads a line of text and returns a string
Common methods of BufferedWriter:
write(String s, int off, int len), write a part of the string
flush(), flushes the stream’s cache
newLine(), writes a line separator
Example:
package com.cn; import java.io.*; import java.nio.charset.StandardCharsets; public class Dom{ public static void main(String[]args) throws Exception{ //Create an array of strings String str[]={"Hello", "I am Li Hua", "Who are you"}; //Create file object File file=new File("E:/","word.txt"); FileWriter fileWriter=new FileWriter(file); BufferedWriter bufferedWriter=new BufferedWriter(fileWriter); for (int k=0;k<str.length;k++){ bufferedWriter.write(str[k]); bufferedWriter.newLine();//OK } bufferedWriter. close(); fileWriter. close(); FileReader fileReader=new FileReader(file); BufferedReader bufferedReader=new BufferedReader(fileReader); String s=null; int i=0; // keep looping if the text is not empty while ((s=bufferedReader. readLine())!=null){ i + + ; System.out.println("th" + i + "line" + s); } bufferedReader. close(); fileReader. close(); } }
Result:
line 1 hello
Line 2 I am Li Hua
line 3 who are you
5. Data input and output stream
The data input and output streams are the DataInputStream and DataOutputStream classes, which allow applications to read basic java data types from the underlying input stream in a machine-independent manner, without worrying about the byte type of the value.
DataOutputStream class method:
- writeBytes(String s)
- writeChars(String s)
- writeUTF(String s)
Methods of the DataInputStream class:
- readUTF()
The readUTF() method can only read what was written by the writeUTF() method.
Example:
package com.cn; import java.io.*; import java.nio.charset.StandardCharsets; public class Dom{ public static void main(String[]args) throws Exception{ //Create an array of strings String str[]={"Hello", "I am Li Hua", "Who are you"}; //Create file object File file=new File("E:/","word.txt"); FileOutputStream fileOutputStream=new FileOutputStream(file); DataOutputStream dataOutputStream=new DataOutputStream(fileOutputStream); dataOutputStream.writeUTF(str[2]); dataOutputStream.writeBytes(str[0]); dataOutputStream.writeChars(str[1]); dataOutputStream. close(); fileOutputStream. close(); FileInputStream fileInputStream=new FileInputStream(file); DataInputStream dataInputStream=new DataInputStream(fileInputStream); System.out.println(dataInputStream.readUTF()); dataInputStream. close(); fileInputStream. close(); } }
Result:
Who are you
6.Zip compressed input and output stream
The construction method of ZipOutputStream: ZipOutputStream(OutputStream out);
Method | Return Value | Explanation |
---|---|---|
putNextEntry(ZipEntry e) | void | Start writing a new ZipEntry, and move the position in the stream to the beginning of the data pointed to by this entry |
write(byte b[],int off,int len) | void | Write byte array to current ZIP entry data |
finish() | void | Complete the content written to the ZIP output stream without closing the OutputStream it cooperates |
setComment(String comment) | void | You can set the comment text of this ZIP file |
Method | Return Value | Explanation |
---|---|---|
read(byte[]b,int off,int len) | int | Read the position of the off offset in the target b array, the length is len bytes |
available() | int | Determine whether the data pointed to by the current entry has been read. Return 0 if read, otherwise return 1 |
closeEntry() | void | Close the current zip entry and locate the stream to read next entry |
skip(long n) | long | skip the specified number of bytes in the current zip entry |
getNexEntry() | ZipEntry | Read the next ZipEntry and move the position in the stream to the data pointed to by the entry |
createZipEntry(String name) | ZipEntry | Create a new ZipEntry object with the specified name parameter |
Example:
package com.cn; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; public class Dome { public static void main(String[] args) throws Exception { File file=new File("E:/","word.zip");//The current decompressed file ZipInputStream zipInputStream;// ZipFile zipFile=new ZipFile(file);//Create decompressed file object zipInputStream=new ZipInputStream(new FileInputStream(file));//Instantiate the object and specify the decompressed file ZipEntry zipEntry=zipInputStream.getNextEntry();//Skip the root directory and get the next ZipEntry while (((zipEntry!=null) & amp; & amp;!zipEntry.isDirectory()) & amp; & amp;!zipEntry.isDirectory()){//If zipEntry is not empty, it is not in the same directory System.out.println("1"); System.out.println(zipEntry.getName()); File file1=new File("D:",zipEntry.getName());//Unzip the file path if (!file1.exists()){//If the file does not exist file1.getParentFile().mkdirs();//Create file parent folder path OutputStream outputStream=new FileOutputStream(file1);// put the directory file into the output stream InputStream inputStream=zipFile.getInputStream(zipEntry);//Use the input stream to read the files in the specified directory in the compressed file int count=0; while ((count=inputStream.read())!=-1){//If there is an output stream, the value can be read outputStream.write(count);//output stream write } outputStream.close();//Close the stream inputStream.close();//Close the stream } zipInputStream.closeEntry();// System.out.println(zipEntry.getName() + "Decompression succeeded"); break; } zipInputStream. close(); } }
Result: