##Prepare internship diary
This is my course experience in preparing for internship. It only records the knowledge I think needs to be recorded and newly learned during the study. What I say is all my personal understanding. If there is any error, please correct it and discuss it. JAVA basic course It's where I study.
2022.01.14 JAVA foundation - singleton mode
2022.01.15 JAVA foundation - exception handling
2022.01.15 JAVA foundation - I/O
preface
Input refers to reading from memory and output refers to writing to memory. General input and output objects are files. Here is a summary of how to create and use file objects, and how to use various input and output streams to read or write file contents.
1, File object
Files and folders are the representatives of File. You can use an absolute path or a relative path to create a File object, but creating a File object does not mean that the File or folder is actually created under this path. To actually create a folder, you need to call the Create method.
import java.io.File; public class TestFile { public static void main(String[] args) { // Absolute path, which represents a folder. You can use this folder to represent the path File f1 = new File("d:/Hello world"); System.out.println("f1 Absolute path to:" + f1.getAbsolutePath()); // Relative path, working directory File f2 = new File("Helloworld.exe"); System.out.println("f2 Absolute path to:" + f2.getAbsolutePath()); // Create a file object with f1 as the parent directory File f3 = new File(f1, "Helloworld.exe"); System.out.println("f3 Absolute path to:" + f3.getAbsolutePath()); } }
There are many built-in methods in the File object, which can query the specific information of the File or folder and create a File.
import java.io.File; import java.util.Date; public class TestFile { public static void main(String[] args) { File f = new File("d:/Hello world/Helloworld.exe"); System.out.println("The current file is:" +f); //Does the file exist System.out.println("Determine whether there is:"+f.exists()); //Is it a folder System.out.println("Determine whether it is a folder:"+f.isDirectory()); //Is it a file (not a folder) System.out.println("Determine whether it is a file:"+f.isFile()); //file length System.out.println("Get the length of the file:"+f.length()); //Last modification time of file long time = f.lastModified(); Date d = new Date(time); System.out.println("Get the last modification time of the file:"+d); //Set the file modification time to 08:00:00 on January 1, 1970 f.setLastModified(0); //File rename File f2 =new File("d:/Hello world/Hello.exe"); f.renameTo(f2); /*Note: you need to have a hello. In D:\Hello world exe Then you can see the corresponding file length, modification time and other information*/; // Returns all files in the current folder (excluding sub files and sub folders) in the form of string array f.list(); // Returns all files in the current folder (excluding sub files and sub folders) in the form of file array File[]fs= f.listFiles(); // Returns the folder where the retrieval is located as a string f.getParent(); // Return to get the folder as a file f.getParentFile(); // Create a folder. If the parent folder skin does not exist, the creation is invalid f.mkdir(); // Create a folder. If the parent folder skin does not exist, the parent folder will be created f.mkdirs(); // Create an empty file. If the parent folder skin does not exist, an exception will be thrown f.createNewFile(); // Therefore, before creating an empty file, the parent directory is usually created f.getParentFile().mkdirs(); // List all drive letters c: d: e: etc f.listRoots(); // Delete file f.delete(); // Delete files at the end of the JVM, which is often used to delete temporary files f.deleteOnExit(); } }
2, Input / output stream
Stream generally refers to data stream, which is a series of data.
When there is data interaction between different media, JAVA uses stream to realize it. For example, reading data from the hard disk to the cache is called input stream from the perspective of program.
The data source can be a file, a database, a network or even other programs.
1. Byte stream
Used to read and write data in bytes. All data stored in the computer is stored in digital form. So letters need to be converted into numbers before they can be stored. Common codes such as ASCII code.
a. Byte input stream
InputStream is not only a byte input stream, but also an abstract class. It only provides method declarations, not specific implementations of methods.
FileInputStream is a subclass of InputStream. Take FileInputStream as an example to read files
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { try { //Prepare file hello Txt the contents are AB and the corresponding ASCII are 65 and 66 respectively File f =new File("d:/Hello world/Hello.txt"); //Create a file based input stream. Note that creating a stream does not mean starting reading FileInputStream fis =new FileInputStream(f); //Create a byte array whose length is the length of the file byte[] all =new byte[(int) f.length()]; //Read all the contents of the file in the form of byte stream, and this is the real start of reading fis.read(all); for (byte b : all) { //Print out 65 66 System.out.println(b); } //Every time the stream is used, it should be closed fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
b. Byte output stream
OutputStream is not only a byte output stream, but also an abstract class. It only provides method declarations, not specific implementations of methods.
FileOutputStream is a subclass of OutputStream. Take FileOutputStream as an example to write data to a file.
Note: if file D: / Hello Txt does not exist. Write out will automatically create the file.
But if it's the file D: / Hello World / Hello Txt, and the directory / Hello world does not exist, an exception will be thrown.
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { try { // Prepare file hello Txt the contents are empty File f = new File("d:/Hello.txt"); // Prepare a byte array with a length of 2 and initialize it with 88 and 89. The corresponding characters are x and Y respectively byte data[] = { 88, 89 }; // Create a file based output stream FileOutputStream fos = new FileOutputStream(f); // Write data to output stream fos.write(data); // Close output stream fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
All streams should be closed normally after use, otherwise it will be detrimental to the progress of the project. For example, in some cases, only one or several streams are allowed to be created. If each stream is not closed after use, it will soon be impossible to create a new stream for others to use.
2. Character stream
Reader character input stream and Writer character output stream are specially used to read and write data in the form of characters.
a. Character input stream
FileReader is a subclass of Reader. Take FileReader as an example to read files.
import java.io.File; import java.io.FileReader; import java.io.IOException; public class TestStream { public static void main(String[] args) { // Prepare file hello Txt the content is AB File f = new File("d:/Hello.txt"); // Create a file based Reader //Here, the creation of the File object is placed in the try, which is one of the ways to close the flow, eliminating the need to call the close method try (FileReader fr = new FileReader(f)) { // Create a character array whose length is the length of the file char[] all = new char[(int) f.length()]; // Read all the contents of the file as a character stream fr.read(all); for (char b : all) { // Print out a and B System.out.println(b); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
b. Character output stream
FileWriter is a subclass of Writer. Take FileWriter as an example to write strings to files.
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class TestStream { public static void main(String[] args) { // Prepare file hello txt File f = new File("d:/Hello.txt"); // Create a file based Writer try (FileWriter fr = new FileWriter(f)) { // Writes data to a file in the form of a character stream String data="asdfghjkl"; char[] cs = data.toCharArray(); fr.write(cs); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3. Cache stream
In fact, the use of byte stream and character stream has great disadvantages. For example, if the access medium is a hard disk, each read-write command of byte stream and character stream will access the hard disk. If the read-write frequency is too high, the performance is not very good.
Cache stream is to solve this problem. When the cache stream is read, more data will be read into the cache at one time. Each read in the future will be accessed in the cache until the data in the cache is read, and then read into the hard disk. When the cache stream writes data, it will first write the data to the cache until the cache is full, and then write these data to the hard disk together.
a. Cache stream read
BufferedReader can read one line of data at a time.
File f = new File("d:/Hello.txt"); // Create file character stream // The parameter of the cache stream must be an existing stream try ( FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); ) { while (true) { // Read one line at a time String line = br.readLine(); if (null == line) break; System.out.println(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
b. Cache stream write
PrintWriter caches the character output stream and can write out one line of data at a time
File f = new File("d:/Hello.txt"); try ( FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter(fw); ) { pw.println("abcdefg"); pw.println("higklmn"); pw.println("opq rst"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
c.flush method
When using the cache stream, sometimes you need to write data to the hard disk immediately. You can't write it until the cache is full. You can use the flush method.
File f =new File("d:/Hello.txt"); //Create file character stream //The cache stream must be based on an existing stream try( FileWriter fr = new FileWriter(f); PrintWriter pw = new PrintWriter(fr); ) { pw.println("abcdefg"); //Force the data in the cache to be written to the hard disk, regardless of whether the cache is full or not pw.flush(); pw.println("hijklmn"); pw.flush(); pw.println("opq rst"); pw.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
4. Data flow
When writing a byte or character stream, if you need to write many int numbers, such as 258 and 456, you will find that the corresponding numbers cannot be separated. Whether they are separated at 258 or 25 is a problem. All other identifiers that need to be written represent segmentation, such as spaces. But data flow can solve the problem of identifier. The writeUTF() and readUTF() of the data stream can be read and written in formatted order.
In this example, Boolean values, integers, and strings are written out sequentially to the file through DataOutputStream. Then read these data in sequence through DataInputStream.
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { write(); read(); } private static void read() { File f =new File("d:/Hello.txt"); try ( FileInputStream fis = new FileInputStream(f); DataInputStream dis =new DataInputStream(fis); ){ boolean b= dis.readBoolean(); int i = dis.readInt(); String str = dis.readUTF(); System.out.println("Read Boolean:"+b); System.out.println("Read integer:"+i); System.out.println("Read string:"+str); } catch (IOException e) { e.printStackTrace(); } } private static void write() { File f =new File("d:/Hello.txt"); try ( FileOutputStream fos = new FileOutputStream(f); DataOutputStream dos =new DataOutputStream(fos); ){ dos.writeBoolean(true); dos.writeInt(1000); dos.writeUTF("abcdefg"); } catch (IOException e) { e.printStackTrace(); } } }
5. Object flow
Object stream refers to the overall transmission of an object to other media in the form of stream. An object is transmitted as a stream, which is called serialization. The class corresponding to the object must implement the Serializable interface. No more examples.
3, Close flow
1. Close in the try code block
Close the file input stream in the scope of try, but this has a disadvantage: if the file does not exist or an exception is thrown due to a problem when reading, this line of code to close the stream will not be executed, which has a huge hidden danger of resource occupation.
try { File f = new File("d:/hello.txt"); FileInputStream fis = new FileInputStream(f); byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } // Close the flow in the try snippet fis.close(); } catch (IOException e) { e.printStackTrace(); }
2. Close in the finally code block
finally, the code block placed after the try catch code block is the part that will be executed after the try catch code block is executed.
This method is the standard way to close the flow
1. First, declare the reference of the stream outside the try. If it is declared inside the try, its scope cannot reach finally
2. Before closing finally, judge whether the reference is empty
3. When closing, try catch again
File f = new File("d:/hello.txt"); FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } finally { // Close the flow in the finally code block if (fis != null){ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3. How to use try(...)
Define the stream in try(). When try,catch or finally ends, it will be closed automatically. All streams implement an interface called autoclosable. Any class that implements this interface can be instantiated in try(). It will be automatically closed at the end of try,catch and finally to recycle relevant resources.
File f = new File("d:/hello.txt"); //When try,catch or finally ends, this method will automatically close the stream try (FileInputStream fis = new FileInputStream(f)) { byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); }