java Foundation
Notes are scattered knowledge points that need to be recited and organized in a sequential manner
Concept, use, principle, difference, scene
1, File stream
1. Concept
A file is where text holds data
Files are operated in the form of streams in programs
Stream: the path of data between the data source (file) and the program (memory)
Input stream: the path of data from data source (file) to program (memory)
Output stream: the path of data from program (memory) to data source (file)
2. Common file operations
1. Constructors and methods for creating file objects
- Method 1: build a File object according to the path
new File(String pathname)
public void create01() { String filePath = "e:\\news1.txt"; File file = new File(filePath); try { file.createNewFile(); System.out.println("File created successfully"); } catch (IOException e) { e.printStackTrace(); } }
Note: the file object here is just an object in a java program. Only when the createNewFile method is executed can the file be truly created on the disk
- Method 2: build according to the parent directory file + child path
new File(File parent,String child)
public void create02() { File parentFile = new File("e:\\"); String fileName = "news2.txt"; File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("Created successfully~"); } catch (IOException e) { e.printStackTrace(); } }
- Method 3: build according to parent directory + child path
new File(String parent,String child)
public void create03() { String parentPath = "e:\\"; String fileName = "news4.txt"; File file = new File(parentPath, fileName); try { file.createNewFile(); System.out.println("Created successfully~"); } catch (IOException e) { e.printStackTrace(); } }
2. Get information about the file
getName
getAbsolutePath
getParent
length
exists
isFileisDirectory
public class FileInformation { public static void main(String[] args) { } //Get file information @Test public void info() { //Create the file object first File file = new File("e:\\news1.txt"); //Call the corresponding method to get the corresponding information //getName,getAbsolutePath,getParent //length,exists,isFile,isDirectory System.out.println("File name=" + file.getName()); System.out.println("File absolute path=" + file.getAbsolutePath()); System.out.println("File parent directory=" + file.getParent()); System.out.println("file size(byte)=" + file.length()); System.out.println("Does the file exist=" + file.exists());//T System.out.println("Is it a file=" + file.isFile());//T System.out.println("Is it a directory=" + file.isDirectory());//F } }
3. Directory operation and file deletion
mkdir() creates a first level directory
mkdirs() creates a multi-level directory
delete() deletes an empty directory or file
2, Principle and classification of IO stream
1. java IO stream principle
- I/O is the abbreviation of Input/Output. I/O technology is a very practical technology for processing data transmission. Such as reading and writing files, network communication, etc.
- In java program, the input / output operation of data is carried out in the way of "stream"
- Various "stream" classes and interfaces are provided under the java.io package to obtain different kinds of data and input or output data through methods
- 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
2. Classification of flow
- According to different operation data units, it is divided into byte stream (8bit) binary file and character stream (by character) text file
- According to the flow direction of the data flow shop, it is divided into input flow and output flow
- According to the different roles of flow, it can be divided into node flow, processing flow / packaging flow
The IO stream of java involves more than 40 classes, which are actually very regular and derived from the above four abstract base classes; The names of subclasses derived from the four classes are all suffixed with their parent class names
3. IO flow system diagram - common classes
IO flow system diagram
Introduction to common classes
1.FileInputStream
public class FileInputStream_ { public static void main(String[] args) { } /*** Show me reading files* Reading of a single byte, Low efficiency * - > use read(byte[] b) */ @Test public void readFile01() { String filePath = "e:\\hello.txt"; int readData = 0; FileInputStream fileInputStream = null; try { //Create a FileInputStream object to read files fileInputStream = new FileInputStream(filePath); //Read one byte of data from the input stream. If no input is available, this method blocks// If - 1 is returned, the reading is completed while ((readData = fileInputStream.read()) != -1){ System.out.print((char)readData);//Convert to char display } } catch (IOException e) { e.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /*** Use read(byte[] b) to read files to improve efficiency */ @Test public void readFile02() { String filePath = "e:\\hello.txt"; //Byte array byte[] buf = new byte[8]; //Read 8 bytes at a time int readLen = 0; FileInputStream fileInputStream = null; try { //Create a FileInputStream object to read files fileInputStream = new FileInputStream(filePath); //Read up to b.length bytes of data from the input stream into the byte array. This method blocks until some input is available. //If - 1 is returned, the reading is completed //If the reading is normal, the number of bytes actually read is returned while ((readLen = fileInputStream.read(buf)) != -1){ System.out.print(new String(buf, 0, readLen));//display } } catch (IOException e) { e.printStackTrace(); } finally { //Close the file stream and free up resources try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2.FileOutputStream
Use FileOutputStream to write in a file. If the file does not exist, the file is created (Note: if the directory already exists.)
Write data to file
public class FileOutputStream01 { public static void main(String[] args) { } /** * Demonstrates using FileOutputStream to write data to a file, * If the file does not exist, it is created */ @Test public void writeFile() { //Create FileOutputStream object String filePath = "e:\\a.txt"; FileOutputStream fileOutputStream = null; try { //Get FileOutputStream object //explain //1. Create new fileoutputstream (filepath). When the content is written, the original content will be overwritten //2. new FileOutputStream(filePath, true) creation method. When the written content is, it is appended to the back of the file fileOutputStream = new FileOutputStream(filePath, true); //Write a byte //fileOutputStream.write('H');// //Write String str = "hsp,world!"; //str.getBytes() can convert string - > byte array //fileOutputStream.write(str.getBytes()); /** *write(byte[] b, int off, int len) *Writes len bytes to this file output stream from the specified byte array at offset off */ fileOutputStream.write(str.getBytes(), 0, 3); } catch (IOException e) { e.printStackTrace(); } finally { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Copy of file
public class FileCopy { public static void main(String[] args) { //After copying the file, copy e:\Koala.jpg to c:\ //Train of thought analysis //1. Create the input stream of the file and read the file into the program //2. Create the output stream of the file and write the read file data to the specified file String srcFilePath = "e:\\Koala.jpg"; String destFilePath = "e:\\Koala3.jpg"; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(srcFilePath); fileOutputStream = new FileOutputStream(destFilePath); //Define a byte array to improve the reading effect byte[] buf = new byte[1024]; int readLen = 0; while ((readLen = fileInputStream.read(buf)) != -1) { //After reading, it is written to the file through fileOutputStream //That is, while reading, write fileOutputStream.write(buf, 0, readLen); //Be sure to use this method } System.out.println("Copy ok~"); } catch (IOException e) { e.printStackTrace(); } finally { try { //Close the input and output streams to free up resources if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
3.FileReader and FileWriter
FileReader common methods:
(1)new FileReader(File/String)
(2) Read: each time a single character is read, the character is returned. If it reaches the end of the file, it returns - 1
(3) read(char []): read multiple characters into the array in batch and return the number of characters read. If - 1 is returned at the end of the file, the relevant APl:
(4) new String(char []): convert char [] to String
(5) new String(char[],off,len): converts the specified part of char [] into a String
FileWriter common methods:
(1) new FileWriter(File/String): overwrite mode, which is equivalent to that the pointer of the stream is at the head end
(2) new FileWriter(File/String,true): append mode, which is equivalent to the flow pointer at the end
(3) write(int): writes a single character
(4) write(char []): writes the specified array
(5) write(char[],off,len): writes the specified part of the specified array
(6) write (string): writes the entire string
(7) write(string,off,len): writes the specified part of the string
Related API: String class: toCharArray(): convert string class to char []
After the FileWriter is used, it must be closed or flushed, otherwise the specified file cannot be written
FileReader uses:
Use FileReader to read the content from story.txt and display it
public class FileReader_ { public static void main(String[] args) { } //Single character read file @Test public void readFile01() { String filePath = "e:\\story.txt"; FileReader fileReader = null; int data = 0; //1. Create FileReader object try { fileReader = new FileReader(filePath); //Read is used for cyclic reading, and a single character is read while ((data = fileReader.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileReader != null) { fileReader.close(); } } catch (IOException e) { e.printStackTrace(); } } } //Character array read file @Test public void readFile02() { System.out.println("~~~readFile02 ~~~"); String filePath = "e:\\story.txt"; FileReader fileReader = null; int readLen = 0; char[] buf = new char[8]; //1. Create FileReader object try { fileReader = new FileReader(filePath); //read(buf) is used for cyclic reading, and the number of characters actually read is returned //If - 1 is returned, it means the end of the file while ((readLen = fileReader.read(buf)) != -1) { System.out.print(new String(buf, 0, readLen)); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileReader != null) { fileReader.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
FileWriter uses:
Write "after the wind and rain, see the rainbow" to the note.txt file. Pay attention to the details
public class FileWriter_ { public static void main(String[] args) { String filePath = "e:\\note.txt"; //Create FileWriter object FileWriter fileWriter = null; char[] chars = {'a', 'b', 'c'}; try { fileWriter = new FileWriter(filePath); //The default is overwrite write // 1) write(int): writes a single character fileWriter.write('H'); // 2) write(char []): writes the specified array fileWriter.write(chars); // 3) write(char[],off,len): writes the specified part of the specified array fileWriter.write("Han Shunping Education".toCharArray(), 0, 3); // 4) write (string): writes the entire string fileWriter.write(" Hello, Beijing~"); fileWriter.write("After the wind and rain, you will see the rainbow"); // 5) write(string,off,len): writes the specified part of the string fileWriter.write("Shanghai Tianjin", 0, 2); //In case of large amount of data, circular operation can be used } catch (IOException e) { e.printStackTrace(); } finally { //Corresponding to FileWriter, you must close the stream or flush to write data to the file //Lao Han knows the reason from the source code /* Look at the code private void writeBytes() throws IOException { this.bb.flip(); int var1 = this.bb.limit(); int var2 = this.bb.position(); assert var2 <= var1; int var3 = var2 <= var1 ? var1 - var2 : 0; if (var3 > 0) { if (this.ch != null) { assert this.ch.write(this.bb) == var3 : var3; } else { this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3); } } this.bb.clear(); } */ try { //fileWriter.flush(); //Close the file stream, equivalent to flush() + close fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("Program end..."); } }
4. Node flow and processing flow
1. Node flow processing flow
Node streams can read and write data from a specific data source, such as FileReader and FileWriter
Processing flow, also known as wrapper flow, is "connected" to the existing flow (node flow or processing flow). It provides more powerful reading and writing functions for programs and is more flexible, such as BufferedReader and bufferedwriter
2. Node flow processing flow list
3. Differences and relations between node flow and processing flow
(1) Node flow is the underlying flow / low-level flow, which is directly connected to the data source.
(2) Processing flow (packaging flow) packaging node flow can not only eliminate the implementation differences of different node flows, but also provide a more convenient method to complete input and output. [source code understanding]
(3) The processing flow (also known as wrapping flow) wraps the node flow and uses the decorator design pattern, which will not be directly connected to the data source [simulation decorator design pattern = "little partner will be very clear]
4. The functions of processing flow are mainly reflected in the following two aspects:
(1) Performance improvement: mainly increase the buffer to improve the efficiency of input and output.
(2) Convenient operation: the processing flow may provide a series of convenient methods to input and output large quantities of data at one time, which is more flexible and convenient to use
5. Processing stream - BufferedReader and BufferedWriter
BufferedReader and BufferedWriter belong to character stream and read data according to characters
When closing the processing flow, just close the outer flow [see the source code for understanding]
BufferedReader uses:
Use BufferedReader to read the text file and display the output on the console
public class BufferedReader_ { public static void main(String[] args) throws Exception { String filePath = "e:\\a.java"; //Create bufferedReader BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath)); //read String line; //Read by line, high efficiency //explain //1. bufferedReader.readLine() reads files by line //2. When null is returned, it indicates that the file has been read while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } //Close the flow. Note here that you only need to close the BufferedReader, because the bottom layer will automatically close the node flow //FileReader. /* public void close() throws IOException { synchronized (lock) { if (in == null) return; try { in.close();//in The new FileReader(filePath) we passed in is closed } finally { in = null; cb = null; } } } */ bufferedReader.close(); } }
BufferedWriter uses:
Use BufferedWriter to write "hello, Han Shunping education" into the file
public class BufferedWriter_ { public static void main(String[] args) throws IOException { String filePath = "e:\\ok.txt"; //Create BufferedWriter //explain: //1. new FileWriter(filePath, true) means to write by appending //2. new FileWriter(filePath), which means to write in the way of overwrite BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath)); bufferedWriter.write("hello, Han Shunping Education!"); bufferedWriter.newLine();//Insert a system related line feed bufferedWriter.write("hello2, Han Shunping Education!"); bufferedWriter.newLine(); bufferedWriter.write("hello3, Han Shunping Education!"); bufferedWriter.newLine(); //Note: Just close the outer stream. The incoming new FileWriter(filePath) will be closed at the bottom bufferedWriter.close(); } }
BufferedReader and BufferedWriter are used together to copy text files
public class BufferedCopy_ { public static void main(String[] args) { //explain //1. BufferedReader and BufferedWriter are installation character operations //2. Do not operate binary files [sound, video, doc, pdf], which may cause file damage //BufferedInputStream //BufferedOutputStream String srcFilePath = "e:\\a.java"; String destFilePath = "e:\\a2.java"; // String srcFilePath = "e:\0245 Han Shunping zero basic Java leads out this.avi"; // String destFilePath = "e:\a2 Han Shunping. avi"; BufferedReader br = null; BufferedWriter bw = null; String line; try { br = new BufferedReader(new FileReader(srcFilePath)); bw = new BufferedWriter(new FileWriter(destFilePath)); //Note: readLine reads a line, but there is no line feed while ((line = br.readLine()) != null) { //Every time a row is read, it is written bw.write(line); //Insert a new line bw.newLine(); } System.out.println("Copy complete..."); } catch (IOException e) { e.printStackTrace(); } finally { //Close flow try { if(br != null) { br.close(); } if(bw != null) { bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
6. Processing stream - BufferedInputStream and BufferedOutputStream
(1) BufferedInputStream is a byte stream. When creating BufferedInputStream, an internal buffer array will be created
(2) BufferedOutputStream is a byte stream that implements buffered output stream. Multiple bytes can be written to the underlying output stream without calling the underlying system for each byte write
Copy using BufferedInputStream and BufferedOutputStream
public class BufferedCopy02 { public static void main(String[] args) { // String srcFilePath = "e:\\Koala.jpg"; // String destFilePath = "e:\\hsp.jpg"; // String srcFilePath = "e:\0245 Han Shunping zero basic Java leads out this.avi"; // String destFilePath = "e:\\hsp.avi"; String srcFilePath = "e:\\a.java"; String destFilePath = "e:\\a3.java"; //Create BufferedOutputStream objectbufferedinputstream object BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //Because FileInputStream is a subclass of InputStream bis = new BufferedInputStream(new FileInputStream(srcFilePath)); bos = new BufferedOutputStream(new FileOutputStream(destFilePath)); //Loop to read the file and write to destFilePath byte[] buff = new byte[1024]; int readLen = 0; //When - 1 is returned, it indicates that the file has been read while ((readLen = bis.read(buff)) != -1) { bos.write(buff, 0, readLen); } System.out.println("File copy complete~~~"); } catch (IOException e) { e.printStackTrace(); } finally { //Close the flow, close the processing flow of the outer layer, and the bottom layer will close the node flow try { if(bis != null) { bis.close(); } if(bos != null) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
7. Object stream - ObjectInputStream and ObjectOutputStream
Look at a demand
1. Save the int data of int num = 100 to the file. Note that it is not 100, but int 100. In addition, int 100 can be recovered directly from the file
2. Save the dog object dog = new dog ("Xiao Huang", 3) to a file and restore it from the file
3. The above requirement is to be able to serialize and deserialize basic data types or objects
serialization and deserialization
1. Serialization is to save the value and data type of data when saving data
2. Deserialization is to recover the value and data type of data when recovering data
3. If an object needs to support serialization mechanism, its class must be serializable. In order to make a class serializable, the class must implement one of the following two interfaces:
Serializable / / this is a tag interface without methods
Externalizable / / the interface has methods to implement, so we generally implement the above Serializable interface
Object flow:
Function: provides methods for serialization and deserialization of basic types or object types
ObjectOutputStream provides serialization
ObjectInputStream provides deserialization
ObjectOutputStream uses:
Use ObjectOutputStream to serialize the basic data type and a Dog object (name, age) and save it to the data.dat file
public class ObjectOutStream_ { public static void main(String[] args) throws Exception { //After serialization, the saved file format is not text, but saved according to its format String filePath = "e:\\data.dat"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath)); //Serialize data to e:\data.dat oos.writeInt(100);// Int - > integer (serializable implemented) oos.writeBoolean(true);// Boolean - > Boolean (serializable is implemented) oos.writeChar('a');// Char - > character (serializable is implemented) oos.writeDouble(9.5);// Double - > double (serializable is implemented) oos.writeUTF("Han Shunping Education");//String //Save a Dog object, and the Dog class implements Serializable oos.writeObject(new Dog("Wangcai", 10, "Japan", "white")); oos.close(); System.out.println("Data saved(serialized form )"); } }
ObjectInputStream uses:
Use ObjectlnputStream to read data.dat and deserialize the recovered data
// 1. Create flow object ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\data.dat")); // 2. Read and pay attention to the sequence System.out.println(ois.readInt()); System.out.println(ois.readBoolean()); System.out.println(ois.readChar()); System.out.println(ois.readDouble()); System.out.println(ois.readUTF()); System.out.println(ois.readObject()); System.out.println(ois.readObject()); System.out.println(ois.readObject()); // 3. Close ois.close(); System.out.println("Read in deserialization(recovery)ok~");
Notes and details:
(1) Read and write in the same order
(2) Serializable is required to serialize or deserialize objects
(3) SerialVersionUID is recommended to be added to serialized classes to improve version compatibility
(4) When serializing an object, all attributes in it are serialized by default, except for members decorated with static or transient
(5) The main function of the transient keyword is to prevent some member attribute variables modified by the transient keyword from being serialized
(6) When serializing an object, it is required that the type of the attribute inside also implement the serialization interface
(7) Serialization is inheritable, that is, if a class has implemented serialization, all its subclasses have implemented serialization by default
8. Standard input / output stream
9. Transform stream - InputStreamReader and OutputStreamWriter
introduce
1. Inputstreamreader: subclass of reader, which can wrap (convert) InputStream (byte stream) into reader (character stream)
2. Outputstreamwriter: subclass of writer, which implements wrapping OutputStream (byte stream) into writer (character stream)
3. When processing plain text data, if using character stream is more efficient and can effectively solve the Chinese problem, it is recommended to convert byte stream into character stream
4. You can specify the encoding format when using (such as UTF-8, GBK, GB2312, iso8859-1, etc.)
InputStreamReader uses:
Program to package (convert) the byte stream FilelnputStream into character stream InputStreamReader, read the file (in utf-8/gbk format), and then package it into BufferedReader
/** *Demonstrates how to use InputStreamReader to transform streams to solve the problem of Chinese garbled code * Convert byte stream FileInputStream to character stream InputStreamReader, and specify the encoding gbk/utf-8 */ public class InputStreamReader_ { public static void main(String[] args) throws IOException { String filePath = "e:\\a.txt"; //unscramble //1. Convert FileInputStream to InputStreamReader //2. Specify the code gbk //InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk"); //3. Transfer InputStreamReader to BufferedReader //BufferedReader br = new BufferedReader(isr); //Put 2 and 3 together BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), "gbk")); //4. Read String s = br.readLine(); System.out.println("Read content=" + s); //5. Turn off the outer flow br.close(); } }
OutputStreamWriter uses:
Programmatically package (convert) the byte stream FileOutputStream into a character stream OutputStreamWriter to write to the file (according to gbk format, other can be specified, such as utf-8)
// 1. Create flow object OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\a.txt"), "gbk"); // 2. Write osw.write("hello,Han Shunping Education~"); // 3. Close osw.close(); System.out.println("Saved successfully~");
10. Print stream - PrintStream and PrintWriter
Print stream has only output stream and no input stream
PrintWriter and PrintStream use:
public class PrintStream_ { public static void main(String[] args) throws IOException { //PrintWriter printWriter = new PrintWriter(System.out); //Printwriter printwriter = new printwriter (New filewriter ("E: \ \ F2. TXT"); / / printstream (byte print stream / output stream) PrintStream out = System.out; //By default, the location of PrintStream output data is standard output, that is, the display /* public void print(String s) { if (s == null) { s = "null"; } write(s); } */ out.print("john, hello"); //Because the bottom layer of print uses write, we can directly call write to print / output out.write("oracle ,Hello".getBytes()); out.close(); //We can modify the location / device of print stream output //1. Modify the output to "e:\f1.txt" //2. "hello, Han Shunping education ~" will be output to e:\f1.txt //3. public static void setOut(PrintStream out) { // checkIO(); // setOut0(out); // native method, modified out // } System.setOut(new PrintStream("e:\\f1.txt")); System.out.println("hello, Han Shunping Education~"); } } printWriter.print("hi, Hello, Beijing~~~~"); printWriter.close(); //flush + close the stream before writing data to the file } }
3, Properties class
1. Let's look at a demand first
2. Traditional method implementation
public class Properties01 { public static void main(String[] args) throws IOException { //Read the mysql.properties file and get the ip, user and pwd BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties")); String line = ""; while ((line = br.readLine()) != null) { //Cyclic reading String[] split = line.split("="); //If we require the specified ip value if("ip".equals(split[0])) { System.out.println(split[0] + "Value is: " + split[1]); } } br.close(); } }
Inconvenient to use, please lead out the - > properties class
3. Properties class
1. Collection class for reading and writing configuration files
2. Format of configuration file:
key = value
key = value
3. Note: key value pairs do not need spaces, and values do not need to be enclosed in quotation marks. The default type is String
4. Common methods for Properties
Load: load the key value pair of the configuration file to the Properties object
list: display data to the specified device
getProperty(key): get the value according to the key
setProperty(key,value): sets the key value pair to the Properties object
Store: store the key value pairs in the Properties to the configuration file. In idea, save the information to the configuration file. If it contains Chinese, it will be stored as unicode code
5. Properties use
public class Properties02 { public static void main(String[] args) throws IOException { //Use the Properties class to read the mysql.properties file //1. Create Properties object Properties properties = new Properties(); //2. Load the specified configuration file properties.load(new FileReader("src\\mysql.properties")); //3. Display the k-v on the console properties.list(System.out); //4. Obtain the corresponding value according to the key String user = properties.getProperty("user"); String pwd = properties.getProperty("pwd"); System.out.println("user name=" + user); System.out.println("The password is=" + pwd); } }
public class Properties03 { public static void main(String[] args) throws IOException { //Use the Properties class to create a configuration file and modify the content of the configuration file Properties properties = new Properties(); //establish //1. If the file does not have a key, it is created //2. If the file has a key, it is modified /* Properties The parent class is Hashtable, and the bottom layer is the core method of Hashtable public synchronized V put(K key, V value) { // Make sure the value is not null if (value == null) { throw new NullPointerException(); }// Makes sure the key is not already in the hashtable. Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> entry = (Entry<K,V>)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value;//If the key exists, replace return old; } } addEntry(hash, key, value, index);//If it is a new k, addEntry return null;} */ properties.setProperty("charset", "utf8"); properties.setProperty("user", "Tom");//Note that when saving, it is the unicode code value in Chinese properties.setProperty("pwd", "888888"); //Store the k-v in a file properties.store(new FileOutputStream("src\\mysql2.properties"), null); System.out.println("Successfully saved the configuration file~"); } }