2021-6-9
1. Use of file class
- java.io.File class: abstract representation of file and file directory path, which is platform independent
- File can create, delete and rename files and directories, but file cannot access the file content itself. If you need to access the file content itself, you need to use input and output streams
- To represent a real File or directory in a java program, there must be a File object, but a File object in a java program may not have a real File or directory
- The File object can be passed as a parameter to the stream constructor
public class FileTest { //Create an instance of the File class @Test public void test1(){ //Constructor 1: File(String filePath) File file1 = new File("hello.txt"); File file2 = new File("D:/Software/JavaProject/guawa210608/src/xyz/guawaz/io"); //Constructor 2: File(String parentPath,String childPath) File file3 = new File("D:/Software/JavaProject/guawa210608/src/xyz/guawaz","io"); //Constructor 3: File(File parentFile,String childPath) File file4 = new File(file3,"hi.txt"); } } //Common methods of File class /* 1.File Class - public String getAbsolutePath() : Get absolute path - public String getPath() : Get path - public String getName() : Get name - public String getParent() : Get the directory path of the upper level file. If there is none, return null - public long length() : Get file length (i.e. number of bytes) cannot get the length of directory - public long lastModified() : Gets the last modification time (in milliseconds) - public String[] list() : Gets the name array of all files or folders in the specified directory - public File[] listFiles() : Gets the File array of all files or folders in the specified directory */ /* 2.File Rename function of class public boolean renameTo(File dest) file.renameTo(file2); */ @Test public void test2(){ File file1 = new File("hello.txt"); Flie file2 = new File("D:/io/hi.txt"); boolean rt = file1.renameTo(file2); System.out.println(rt); //To ensure that file1 actually exists and file2 does not exist, return true //The function is to cut file1 to the path specified by file2 and rename it to the file name of file2 } /* 3.File Class judgment function - public boolean isDirectory() : Determine whether it is a file directory - public boolean isFile() : Determine whether it is a file - public boolean exists() : Judge whether it exists - public boolean canRead() : Judge whether it is readable - public boolean canWrite() : Determine whether it is writable - public boolean isHidden() : Determine whether to hide */ /* 4.File Class creation function (actually created in the hard disk) - public boolean createNewFile() : Create a file. If the file exists, it will not be created and false will be returned - public boolean mkdir() : Create a file directory. If the directory exists, it will not be created. If the upper directory of this file directory does not exist, it will not be created - public boolean mkdirs() : Create a file directory. If the upper directory of this file directory does not exist, create it together If there is no write letter path for the created file or file directory, it is under the project path by default */ /* 5.File Class deletion function - public boolean delete() : Delete file or folder To delete a file directory, the file directory cannot contain files or file directories */ @Test public void test(){ //Creation and deletion of files File file1 = new File(hi.txt); if(!file1.exists()){ file1.createNewFile(); System.out.println("Created successfully"); }else{ file1.delete(); System.out.println("Delete succeeded"); } } @Test public void test(){ //Creation and deletion of file directory File file1 = new File("d:\\io\\io1\\io2"); boolean mkdir = file1.mkdir(); //io1 does not exist, creation failed if(mkdir){ System.out.println("Created successfully 1"); } File file2 = new File("d:\\io\\io1\\io3"); boolean mkdir = file2.mkdir(); //io1 does not exist, created successfully if(mkdir){ System.out.println("Created successfully 2"); } } //The File class involves the creation, deletion, renaming and modification time of files or File directories //Methods such as file size do not involve writing or reading file contents. If you need to read //Operations such as or writing file contents must be completed using IO streams //Objects of subsequent File classes are often passed as parameters to the stream constructor to indicate the "end point" of reading or writing /*Exercise 1: determine whether there is a suffix named in the specified directory jpg file, if any, output the name of the file*/ /*Exercise 2: (1) traverse all file names in the specified directory, including the files in the sub file directory (2)Calculates the amount of space occupied by the specified directory (3)Delete all files under the specified file directory */
2. IO flow principle and flow classification
- IO is the abbreviation of Input and Output. IO technology is a very practical technology for processing data transmission between devices. Such as reading and writing files, network communication, etc.
- In Java programs, the input and output operations of data are carried out in the form of "stream"
- Java. Various "stream" classes and interfaces are provided under the IO package to transmit different kinds of data
- input: read external data (data from disk, optical disc and other storage devices) into the program (memory)
- Output: output program (memory) data to disk, optical disc and other storage devices
- Classification of flow:
- According to different data units, it is divided into byte stream (8bit) and character stream (16bit)
- According to the flow direction of data flow, it is divided into input flow and output flow
- According to the different roles of the flow, it is divided into node flow and processing flow
package xyz.guawaz.io; import org.junit.Test; import java.io.File; import java.io.FileReader; import java.io.IOException; /** * @auther guawaz * @create 2021-06-08-16:56 * * * * 1, Classification of flow * 1.Operation data unit: byte stream, character stream * 2.Data flow direction: input flow and output flow * 3.Roles of flow: node flow and processing flow * 2, Flow architecture * Abstract base class node stream buffer stream (a kind of processing stream) * InputStream FileInputStream BufferedInputStream * OutputStream FileOutputStream BufferedOutputStream * Reader FileReader BufferedReader * Writer FileWriter BufferedWriter * * * */ public class FileReadWriterTest { @Test public void testFileReader() throws IOException { //1. Instantiate the object of File class to indicate the File to be operated File file = new File("hello.txt"); //2. Provide specific flow FileReader fr = new FileReader(file); //3. Data reading //read(): returns a character read in. If it reaches the end of the file, it returns - 1 // int data = fr.read(); // while(data != -1){ // System.out.print((char)data); // data = fr.read(); // } int data; while((data = fr.read())!= -1){ System.out.println((char)data); } //4. Closure of flow fr.close(); } } //To ensure that the stream resources can be closed, try catch finally is used. The modification is as follows: public class FileReadWriterTest { @Test public void testFileReader() throws { FileReader fr = null; try { //1. Instantiate the object of File class to indicate the File to be operated File file = new File("hello.txt"); //2. Provide specific flow fr = new FileReader(file); //3. Data reading //read(): returns a character read in. If it reaches the end of the file, it returns - 1 int data; while((data = fr.read())!= -1){ System.out.println((char)data); } } catch (IOException e) { e.printStackTrace(); } finally { try { //4. Close the flow if (fr!=null) //Prevent fr = new FileReader(file); Something's wrong with this line fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } //The read file must exist, otherwise FileNotFoundException will be reported //Upgrade the operation of the read() method and use its overloaded method @Test public void testFileReader1() { FileReader fr = null; try { //1. Instantiate the object of File class to indicate the File to be operated File file = new File("hello.txt"); //2. Provide specific flow fr = new FileReader(file); //3. Data reading //read(): returns a character read in. If it reaches the end of the file, it returns - 1 char[] cbuf = new char[5]; int len; while((len = fr.read(cbuf))!= -1){ //Mode 1: //Wrong writing for(int i = 0 ;i < cbuf.length; i++){ System.out.println(cbuf[i]); } //Correct writing for(int i = 0 ;i < len; i++){ System.out.println(cbuf[i]); } /* //Mode 2: //Wrong writing String str = new String(cbuf); System.out.println(str); //Correct writing String str = new String(cbuf,0,len); System.out.println(str); */ } } catch (IOException e) { e.printStackTrace(); } finally { try { //4. Close the flow if (fr!=null) //Prevent fr = new FileReader(file); Something's wrong with this line fr.close(); } catch (IOException e) { e.printStackTrace(); } } } /* *Write data from memory to a file on the hard disk * * 1.File The file in the corresponding hard disk may not exist. If it does not exist, it will be created * 2.File If the file in the corresponding hard disk exists * If the constructor used by the stream is: FileWriter(file,append: false)/FileWriter(file): the output data operation will overwrite the original file content * If the constructor used by the stream is: FileWriter(file,append: true): the output operation is to add content to the original file content * * * */ @Test public void testFileWriter(){ FileWriter fileWriter = null; try { //1. Create a File object File file = new File("hello.txt"); //2. Create output stream object fileWriter = new FileWriter(file); //3. Output data fileWriter.write("I have a dream!"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileWriter != null) //4. Close stream resources fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } /* *Read in before you write out * */ @Test public void testFileReaderFileWriter(){ FileReader fileReader = null; FileWriter fileWriter = null; try { //1. Create a File object to indicate the read in and write out files File srcFile = new File("hello.txt"); File destFile = new File("hello2.txt"); //2. Create input stream and output stream objects fileReader = new FileReader(srcFile); fileWriter = new FileWriter(destFile); //3. Read data and output data char[] cbuf = new char[5]; int len; while((len = fileReader.read(cbuf)) != -1){ // for (int i = 0 ; i < len ; i ++){ // fileWriter.write(cbuf[i]); // } String str = new String(cbuf); fileWriter.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileWriter != null) { //4. Close stream resources fileWriter.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (fileReader != null) { //4. Close stream resources fileReader.close(); } } catch (IOException e) { e.printStackTrace(); } //Mode II // try { // if (fileWriter != null) { // //4. Close stream resource // fileWriter.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (fileReader != null) { // //4. Close stream resource // fileReader.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // } } }
3. Node stream (or file stream)
- Picture files cannot be processed using character streams
package xyz.guawaz.io; import org.junit.Test; import java.io.*; /** * @auther guawaz * @create 2021-06-08-20:50 */ public class FileInputOutputStreamTest { @Test public void testFileInputOutputStream() { FileInputStream fis = null; FileOutputStream fos = null; try { //1. Documentation File srcfile = new File("dream.png"); File destfile = new File("dream1.png"); //2. Flow generation fis = new FileInputStream(srcfile); fos = new FileOutputStream(destfile); //3. Read and write data byte[] buffer = new byte[5]; int len; while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Close the flow try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
4. One of the processing streams: buffer stream
package xyz.guawaz.io; import org.junit.Test; import java.io.*; /** * @auther guawaz * @create 2021-06-08-23:13 * * One of the processing streams: the use of buffer streams * 1.Buffer stream * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter *2.Function: improve the read and write speed of the stream * */ public class BufferedTest { @Test public void bufferedStreamTest(){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1. Documentation File srcFile = new File("dream.png"); File destfile = new File("dream2.png"); //2. Flow generation //2.1 node flow FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destfile); //2.2 buffer flow bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3. Read and write data byte[] buffer = new byte[10]; int len; while((len = bis.read(buffer)) != -1){ //data encryption //for(int i = 0 ; i < len ; i ++){ // buffer[i] = (byte)(buffer[i]^5); //} bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Close the flow (closing the buffer flow will automatically close the node flow) try { if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void bufferedReaderBufferedWriterTest(){ BufferedReader br = null; BufferedWriter bw = null; try { //1. Documentation File srcfile = new File("hello.txt"); File destfile = new File("hello1.txt"); //2. Flow generation //2.1 node flow FileReader fr = new FileReader(srcfile); FileWriter fw = new FileWriter(destfile); //2.2 buffer flow br = new BufferedReader(fr); bw = new BufferedWriter(fw); //3. Read and write data char[] buffer = new char[10]; int len; while((len = br.read(buffer)) != -1){ bw.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Close stream resources try { if (br != null) br.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bw != null) bw.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void bufferedReaderBufferedWriterTest1(){ BufferedReader br = null; BufferedWriter bw = null; try { //Create files and corresponding streams br = new BufferedReader(new FileReader(new File("hello.txt"))); bw = new BufferedWriter(new FileWriter(new File("hello3.txt"))); //3. Read and write data //Mode 1 // char[] buffer = new char[10]; // int len; // while((len = br.read(buffer)) != -1){ // bw.write(buffer,0,len); // } //Mode II String data; while((data = br.readLine()) != null){ bw.write(data + "\n"); //bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Shut off try { if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (bw != null) { bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * @auther guawaz * @create 2021-06-08-23:13 * Gets the number of occurrences of a character in the text file and writes it to the file * Idea: traverse each character of the text file and store the number of characters in the Map */ @Test public void wordCount(){ FileReader fr = null; FileWriter fw = null; try { File file = new File("hello.txt"); fr = new FileReader(file); fw = new FileWriter(file,true); Map<Character,Integer> map = new HashMap<>(); int c = 0; while((c= fr.read()) != -1){ char ch = (char)c; if(map.get(ch) == null){ map.put(ch,1); }else{ map.put(ch, map.get(ch) + 1); } } //Traverse the map and write data Set<Map.Entry<Character,Integer>> entrySet = map.entrySet(); fw.write("\n"); for(Map.Entry<Character,Integer> entry : entrySet){ switch(entry.getKey()){ case ' ': fw.write("Space=" + entry.getValue()); break; case '\t': fw.write("tab key="+entry.getValue()); break; case '\r': fw.write("enter=" + entry.getValue()); break; case '\n': fw.write("Line feed=" + entry.getValue()); break; default: fw.write(entry.getKey() + "=" + entry.getValue()); break; } fw.write("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (fw != null) { fw.close(); } } catch (IOException e) { e.printStackTrace(); } } }
5. Processing flow 2: conversion flow
- Conversion stream provides conversion between character stream and byte stream
- The Java API provides two transformation streams: InputStreamReader and OutputStreamWriter
- When the data in the byte stream is all characters, the operation of converting to character stream is more efficient
- Many times, we use transform stream to deal with the problem of file scrambling and realize the functions of encoding and decoding
package xyz.guawaz.io; import org.junit.Test; import java.io.*; /** * @auther guawaz * @create 2021-06-09-11:20 * * Processing flow 2: use of conversion flow * 1.Conversion stream: belongs to character stream * * InputStreamReader:Converts a byte input stream to a character input stream * OutputStreamWriter:Converts a character output stream to a byte output stream * * 2.Function: provide conversion between character stream and byte stream * * 3.Decoding: byte, byte array -- > character, string * Encoding: character, string ----- > byte, byte array * * 4.character set * * */ public class InputStreamReaderTest { @Test public void test1(){ InputStreamReader isr = null; try { FileInputStream fis = new FileInputStream("hello.txt"); isr = new InputStreamReader(fis,"utf-8"); char[] cbuf = new char[5]; int len; while((len = isr.read(cbuf)) != -1){ String str = new String(cbuf,0,len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* * * Use InputStreamReader and OutputStreamWriter together * * */ @Test public void test2(){ InputStreamReader isr = null; OutputStreamWriter osw = null; try { File srcfile = new File("hello.txt"); File destfile = new File("hello_gbk.txt"); FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); isr = new InputStreamReader(fis,"utf-8"); osw = new OutputStreamWriter(fos,"gbk"); char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ osw.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } if (osw != null) { try { osw.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
- character set
Common coding tables: ASCII:American standard information interchange code, which represents characters in 7 bits of a byte ISO8859-1: Latin code table, European code table, using 8 bits of a byte to represent characters GB2312: Chinese character coding table, up to two byte coded characters GBK: Chinese character coding table upgrade, including more Chinese characters, up to two byte coded characters Unicode: The international standard coding table integrates all characters currently used by human beings. Each character is assigned a unique character code, and all text is represented by two bytes UTF-8: The coding method of side length can be 1~4 Bytes to one character per hour
6. Standard input / output streams and other streams
Processing flow 6:Object flow objectInputStream and OjbectOutputSteam A processing stream used to store and read basic data type data or objects. Its strength is that it can To handle Java Objects in can be written to the data source, and objects can also be restored from the data source. serialize:use ObjectOutputStream Class holds the mechanism for deserialization of basic type data or objects:use ObjectInputStream Class to read basic type data or objects ObjectOutputStream and ObjectInputStream Cannot serialize static and ltransient Decorated member variable object serialization ●The object serialization mechanism allows Java Object into a platform independent binary stream, which allows the binary stream to be permanently stored on disk or transmitted to another network node over the network. When other programs get this binary stream, they can restore it to the original Java object ●The advantage of serialization is that any can be implemented Serializable The object of the interface is converted into byte data so that it can be restored during saving and transmission ●Serialization is RMI (Remote Method lnvoke -The parameters and return values of remote method call) procedures must implement the mechanism, and RMI yes JavaEE The basis of. Therefore, the serialization mechanism is JavaEE Foundation of platform ●If an object needs to support serialization mechanism, the class to which the object belongs and its properties must be serializable. In order for a class to be serializable, the class must implement one of the following two interfaces. Apricot will throw NotSerializableException abnormal > Serializable > Externalizable
package xyz.guawaz.io; import org.junit.Test; import java.io.*; /** * @auther guawaz * @create 2021-06-09-17:24 */ public class ObjectInputOutputStreamTest { @Test public void testObjectOutputStream(){ ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("object.dat")); oos.writeObject(new String("I Love Beijing Tiananmen ")); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { } if (oos != null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void testObjectIntputStream() { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("object.dat")); Object obj = ois.readObject(); String str = (String)obj; System.out.println(str); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { } if (ois != null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } }
- Serialization and object flow of custom classes
- The custom class must implement the Serializable interface and have the global constant serialVersionUID
package xyz.guawaz.io; import java.io.Serializable; import java.util.Objects; /** * @auther guawaz * @create 2021-06-09-18:08 */ public class Person implements Serializable { public static final long serialVersionUID = 45678912254L; private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } } //---------------------------------------------------------------------------------- package xyz.guawaz.io; import org.junit.Test; import java.io.*; /** * @auther guawaz * @create 2021-06-09-17:24 */ public class ObjectInputOutputStreamTest { @Test public void testObjectOutputStream(){ ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("object.dat")); oos.writeObject(new String("I Love Beijing Tiananmen ")); oos.flush(); oos.writeObject(new Person("Guawaz",24)); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { } if (oos != null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void testObjectIntputStream() { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("object.dat")); Object obj = ois.readObject(); String str = (String)obj; System.out.println(str); Object obj1 = ois.readObject(); Person person = (Person)obj1; System.out.println(person); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { } if (ois != null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } }
- serialVersionUID is used to indicate compatibility between different versions of a class. In short, its purpose is to use serialized objects for version control, and whether each version is compatible when deserialized.
- If the class does not show the definition of this static constant, its value is automatically generated by the Java runtime environment according to the internal details of the class. If instance variable of the class is modified, serialVersionUID may change, so declaration must be displayed.
- Except that the current class needs to implement the Serializable interface, all its internal attributes must also be Serializable (by default, the basic data type is Serializable)
- Member variables decorated with static and transient cannot be serialized
- Serialization is the basis of the Java EE platform. It usually converts the content to be serialized into a special format string: json
7. Random access file stream RandomAccessFile class
-RandomAccessFile Class declaration in java.io Package, but directly inherit and java.lang.Object Class, And it does DataInput and DataOutput Interface, which means that this class can read and write. -RandomAccessFile Class supports "random access", and the program can directly jump to any location of the file Read write file - RandomAccessFile The object contains a record pointer to indicate the position of the current read and write location. RandomAccessFile Class object can move the record pointer freely: >long getFilePointer():Gets the current position of the file record pointer >void seek(long pos):Position the file record pointer to pos position
package xyz.guawaz.io; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; /** * @auther guawaz * @create 2021-06-09-19:44 * * If RandomAccessFile is used as the output stream, it will be created automatically if the file written out does not exist * If the file exists, the original file content will be overwritten (if the file content is not a file, it will be overwritten from the beginning by default) * * When creating an instance of RandomAccessFile class, you need to specify a mode parameter, which specifies the access mode of RandomAccessFile * r:Open as read-only * rw:Open for reading and writing * rwd:Open for reading and writing; Synchronize file content updates * rws:Open for reading and writing; Synchronize file content and metadata updates */ public class RandomAccessFileTest { @Test public void test1(){ RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try { //1 raf1 = new RandomAccessFile("dream.png", "r"); raf2 = new RandomAccessFile("dream3.png", "rw"); //2 byte[] buffer = new byte[20]; int len; while((len = raf1.read(buffer)) != -1){ raf2.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //3 if (raf1 != null) { try { raf1.close(); } catch (IOException e) { e.printStackTrace(); } } if (raf2 != null) { try { raf2.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* If RandomAccessFile is used as the output stream, it will be created automatically if the file written out does not exist If the file exists, the original file content will be overwritten (if the file content is not a file, it will be overwritten from the beginning by default) */ @Test public void test2() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw"); raf1.write("xyz".getBytes()); raf1.close(); } /* Using RandomAccessFile to achieve the effect of data insertion */ @Test public void test3() throws FileNotFoundException { RandomAccessFile raf1 = null; try { raf1 = new RandomAccessFile("hello.txt", "rw"); raf1.seek(3); //Save all data after pointer 3 to StringBuilder StringBuilder sb = new StringBuilder((int)new File("hello.txt").length()); byte[] buffer = new byte[20]; int len; while ((len = raf1.read(buffer)) != -1){ sb.append(new String(buffer,0,len)); } raf1.seek(3); raf1.write("xyz".getBytes()); raf1.write(sb.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (raf1 != null) { try { raf1.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Java NIO
-Java NIO is from jdk1 4. A new set of IO API introduced from the beginning can replace the standard Java IO API. NIO has the same function and purpose as the original IO, but the use method is completely different. NIO is buffer oriented and channel based, while IO is stream oriented. NIO can read and write files more efficiently
- The Java API provides two sets of NIO, one for standard input / output IO and the other for network programming NIO
|----java.nio.channels.Channel |----FileChannel:Process local files |----SocketChannel: TCP The of client in network programming Channel |----ServerSocketChannel: TCP Of server in network programming Channel |----DatagramChannel: UDP Of sender and receiver in network programming Channel
- With the release of JDK7, Java has greatly extended NIO and enhanced its support for file processing and file system features, so that we call it NIO 2. NIO has become an increasingly important part of file processing
- NIO.2. Use of Path, Paths and Files classes
- Early Java Only one is provided File Class to access the file system, but File The function of class is relatively limited The performance of the method provided is also not high. Moreover, most methods only return failure when there is an error and do not provide exception information. - NIO.2 In order to make up for this deficiency, the Path Interface, which represents a platform independent platform path, describes The location of the file in the directory structure. Path Can be seen as File The upgraded version of the class, and the actual referenced resources may not exist. - In the past I0 Operations are written like this: import java.io.File; File file = new File("index.html"); But in Java7 In, we can write like this: import java.nio.file.Path; import java.nio.file.Paths; Path path = Paths.get("index.html"); - At the same time, NIO.2 stay java.nio.file The package also provides Files,Paths Tools, Files contain A large number of static tools and methods are used to manipulate files; Paths Contains two returns Path Static factory method. The commonly used methods will not be expanded. We'll talk about them when we use them
Use the third-party jar package to read and write data
- ohhhhhhhhhhhhhhhhhhhhhhhhhhhhh
- Right click - > New - > Directory - > LIBS + OK - > Ctrl + V paste in - > right click - > Add as library