2.1 document object
Files and folders are represented by File
-
Create a file object
Create a File object using an absolute path or a relative path
package file; import java.io.File; public class TestFile { public static void main(String[] args) { // Absolute path File f1 = new File("d:/LOLFolder"); System.out.println("f1 Absolute path to:" + f1.getAbsolutePath()); // Relative path, relative to the working directory, if in eclipse, is the project directory File f2 = new File("LOL.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, "LOL.exe"); System.out.println("f3 Absolute path to:" + f3.getAbsolutePath()); } }
-
File common methods 1
Note 1: you need a LOL.exe in D:\LOLFolder to see the corresponding file length, modification time and other information
Note 2: the renameTo method is used to modify the physical File name, but does not modify the name attribute of the File object.
package file; import java.io.File; import java.util.Date; public class TestFile { public static void main(String[] args) { File f = new File("d:/LOLFolder/LOL.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 January 1970 1 08:00:00 f.setLastModified(0); //File rename File f2 =new File("d:/LOLFolder/DOTA.exe"); f.renameTo(f2); System.out.println("hold LOL.exe Renamed DOTA.exe"); System.out.println("Note: you need to D:\\LOLFolder There is one LOL.exe,\r\n Then you can see the corresponding file length, modification time and other information"); } }
-
File common methods 2
package file; import java.io.File; import java.io.IOException; public class TestFile { public static void main(String[] args) throws IOException { File f = new File("d:/LOLFolder/skin/garen.ski"); // 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(); } }
-
Exercise - traversing folders
Generally speaking, the operating system will be installed on Disk C, so there will be a C:\WINDOWS directory.
Traverse all files in this directory (without traversing subdirectories)
Find the largest and smallest (non-zero) of these files and print out their file names
Note: the minimum file length cannot be 0
package file; import java.io.File; public class TestFile { public static void main(String[] args) { File f = new File("c:\\windows"); File[] fs = f.listFiles(); if(null==fs) return; long minSize = Integer.MAX_VALUE; long maxSize = 0; File minFile = null; File maxFile = null; for (File file : fs) { if(file.isDirectory()) continue; if(file.length()>maxSize){ maxSize = file.length(); maxFile = file; } if(file.length()!=0 && file.length()<minSize){ minSize = file.length(); minFile = file; } } System.out.printf("The largest file is%s,Its size is%,d byte%n",maxFile.getAbsoluteFile(),maxFile.length()); System.out.printf("The smallest file is%s,Its size is%,d byte%n",minFile.getAbsoluteFile(),minFile.length()); } }
-
Exercise - traversing subfolders
Traversal of folders using recursion
package file; ![image.png](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0fb606b0616d4de291553986e8058a93~tplv-k3u1fbpfcp-watermark.image?) import java.io.File; public class TestFile { static long minSize = Integer.MAX_VALUE; static long maxSize = 0; static File minFile = null; static File maxFile = null; //Use recursion to traverse the sub files of a folder public static void listFiles(File file){ if(file.isFile()){ if(file.length()>maxSize){ maxSize = file.length(); maxFile = file; } if(file.length()!=0 && file.length()<minSize){ minSize = file.length(); minFile = file; } return; } if(file.isDirectory()){ File[] fs = file.listFiles(); if(null!=fs) for (File f : fs) { listFiles(f); } } } public static void main(String[] args) { File f = new File("c:\\windows"); listFiles(f); System.out.printf("The largest file is%s,Its size is%,d byte%n",maxFile.getAbsoluteFile(),maxFile.length()); System.out.printf("The smallest file is%s,Its size is%,d byte%n",minFile.getAbsoluteFile(),minFile.length()); } }
2.2 what is flow
What is a stream? A stream is a series of data
-
What is flow
When there is data interaction between different media, JAVA uses stream to realize it. The data source can be a file, a database, a network or even other programs.
For example, reading the data of a file into a program is called input stream: input stream: InputStream output stream from the perspective of the program
-
File input stream
The following code establishes a file input stream, which can be used to read data from the file on the hard disk to the JVM (memory).
At present, the code only establishes the stream and has not started reading. The real reading will be explained in the next chapter.
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { try { File f = new File("d:/lol.txt"); // Create a file based input stream FileInputStream fis = new FileInputStream(f); // Through this input stream, the data can be read from the hard disk to the Java virtual machine, that is, to the memory } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
-
Exercise flow
public class TestStream { public static void main(String[] args) { try{ File f = new File("d:/lol.txt"); FileOutputStream fos = new FileOutputStream(f); }catch (IOException e){ e.printStackTrace(); } } }
2.3 byte stream
InputStream byte input stream, OutputStream byte output stream, which is used to read and write data in bytes.
-
ASCII code concept
All data stored in the computer is stored in digital form. So letters need to be converted into numbers before they can be stored. For example, a corresponds to the number 65 and a corresponds to the number 97 Different letters and symbols correspond to different numbers, which is a code table. ASCII is such a code table. It only contains simple English letters, symbols, numbers, etc. It doesn't include Chinese, German, Russian and other complex.
-
Reads the contents of the file as a byte 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
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { try { //Prepare the file lol.txt, where the contents are AB and the corresponding ASCII are 65 and 66 respectively File f =new File("d:/lol.txt"); //Create a file based input stream FileInputStream fis =new FileInputStream(f); //Create a byte array whose length is the length of the file byte[] all =new byte[(int) f.length()]; //Reads all the contents of the file as a byte stream 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(); } } }
-
Writes data to a file as a byte 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: / lol2 Txt does not exist. Write out will automatically create the file. But if it is the file D: / xyz / lol2 Txt, and the directory xyz does not exist, an exception will be thrown
package stream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { try { // Prepare file lol2 Txt the contents are empty File f = new File("d:/lol2.txt"); // Prepare a byte array with a length of 2 and initialize it with 88,89 //The corresponding characters are x and y 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(); } } }
-
Exercise - writing data to a file
An example of writing data to a file in the form of byte stream, when lol2 When TXT does not exist, lol2.txt is automatically created Txt file. However, if you are writing data to D: / xyz / lol2 Txt, and the directory xyz does not exist, an exception will be thrown. So how to create xyz directory automatically? If it is a multi-layer directory, D: / xyz / ABC / def / lol2 What about TXT?
// Prepare file lol2 Txt the contents are empty File f = new File("d:/xyz/abcd/lol.txt"); //Get the directory where the file is located File dir = f.getParentFile(); if (!dir.exists()){ //dir.mkdir(); // Using MKDIR throws an exception because the parent directory of the directory does not exist dir.mkdirs(); //Using mkdirs will create directories that do not exist }
-
Exercise - splitting files
Find a file larger than 100k, split it into multiple sub files according to 100k, and end with the number as the file name. For example, the file eclipse Exe, the size is 309k. After splitting, it becomes eclipse exe-0 eclipse.exe-1 eclipse.exe-2 eclipse.exe-3
package com.company; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; public class TestStream { /** * The idea of splitting is to read all the contents of the source file into memory, and then divide them into sub files one by one from memory * @param srcFile Source file to split * @param eachSize Split according to this size */ private static void splitFile(File srcFile,int eachSize){ if (srcFile.length() == 0) throw new RuntimeException("The file length is 0 and cannot be split"); byte[] fileContent = new byte[(int) srcFile.length()]; try { //Create a file based input stream FileInputStream fis =new FileInputStream(srcFile); fis.read(fileContent); fis.close(); }catch (IOException e){ e.printStackTrace(); } // Calculate how many files need to be divided into int fileNumber; if (0 == fileContent.length % eachSize) fileNumber = (int) (fileContent.length / eachSize); else fileNumber = (int) (fileContent.length / eachSize) + 1; for (int i = 0;i < fileNumber;i++){ String eachFileName = srcFile.getName() + "-" + i; File eachFile = new File(srcFile.getParent(),eachFileName); byte[] eachContent; // Copy some data from the contents of the source file to the sub file // Except for the last file, all other files are 100k in size // The size of the last file is remaining if(i != fileNumber-1){ eachContent = Arrays.copyOfRange(fileContent,eachSize*i,eachSize); } else { eachContent = Arrays.copyOfRange(fileContent, eachSize * i, fileContent.length); } try { // Write it out FileOutputStream fos = new FileOutputStream(eachFile); fos.write(eachContent); fos.close(); System.out.printf("Output sub file%s,Its size is %d byte%n", eachFile.getAbsoluteFile(), eachFile.length()); } catch (IOException e){ e.printStackTrace(); } } } public static void main(String[] args) { int eachSize = 100 * 1024; // 100k File srcFile = new File("d:/eclipse.exe"); splitFile(srcFile, eachSize); } }
-
Exercise - merge files
Merge the above split files into one original file.
To verify that the merge is correct
package com.company; import java.io.*; import java.util.Arrays; public class TestStream { /** * The idea of merging is from eclipse Exe-0 starts, reads a file, and starts writing to eclipse Exe until no files can be read * @param folder * The directory where the files to be merged are located * @param fileName * Name of the file to be merged * @throws FileNotFoundException */ private static void mergeFile(String folder, String fileName){ try { // Merged target file File destFile = new File(folder, fileName); FileOutputStream fos = new FileOutputStream(destFile); int index = 0; while (true){ //Sub file File eachFile = new File(folder, fileName + "-" + index++); //If the sub file does not exist, it ends if (!eachFile.exists()) break; //Read the contents of the sub file FileInputStream fis = new FileInputStream(eachFile); byte[] eachContent = new byte[(int) eachFile.length()]; fis.read(eachContent); fis.close(); //Write out the contents of the sub file fos.write(eachContent); fos.flush(); System.out.printf("Handle sub file %s Write out to target file%n",eachFile); } fos.close(); System.out.printf("Last destination file size:%,d byte" , destFile.length()); }catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { mergeFile("d:/", "eclipse.exe"); } }
2.4 method of closing flow
All streams, whether input or output, should be closed after use. If it is not closed, it will waste resources. When the equivalent is large, it will affect the normal development of business.
-
Close in try
Close the file input stream in the scope of try. In the previous examples, this method is used. 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 flow will not be executed, resulting in a huge hidden danger of resource occupation. Not recommended
try { File f = new File("d:/lol.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 flow in try fis.close(); } catch (IOException e) { e.printStackTrace(); }
-
Close in finally
This is the standard way to close the flow
-
First, declare the reference of the stream outside the try. If it is declared inside the try, its scope cannot reach finally
-
Before finally closing, judge whether the reference is empty
-
When closing, you need to try catch again
This is a standard and rigorous way to close the flow, but it seems very cumbersome. Therefore, when writing unimportant or testing code, the above hidden try method will be adopted, because it is not troublesome~
public static void main(String[] args) { File f = new File("d:/lol.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 finally if (null != fis) try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
-
How to use try()
Define the flow in try(). When try,catch or finally ends, it will be automatically closed. This way of writing code is called try with resources, which is a technology supported from JDK7
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.
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { File f = new File("d:/lol.txt"); //Define the flow in try(). When try,catch or finally ends, it will be closed automatically 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(); } } }
2.5 character stream
Reader character input stream and Writer character output stream are specially used to read and write data in the form of characters.
-
Read file using character stream
FileReader is a subclass of Reader. Take FileReader as an example to read files.
ackage stream; import java.io.File; import java.io.FileReader; import java.io.IOException; public class TestStream { public static void main(String[] args) { // Prepare the file lol.txt, which contains AB File f = new File("d:/lol.txt"); // Create a file based Reader 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(); } } }
-
Write string to file using character stream
FileWriter is a subclass of Writer. Take FileWriter as an example to write strings to files
package stream; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class TestStream { public static void main(String[] args) { // Prepare file lol2 txt File f = new File("d:/lol2.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="abcdefg1234567890"; char[] cs = data.toCharArray(); fr.write(cs); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
-
Exercise - file encryption
Prepare a text file (non binary), which contains ASCII characters and Chinese characters, and design a method.
public static void encodeFile(File encodingFile, File encodedFile);
In this method, the contents of the encodingFile are encrypted and then saved to the encoded file. Encryption algorithm: Number: if it is not a number of 9, add 1 to the original basis. For example, 5 becomes 6, 3 becomes 4, if it is a number of 9, it becomes 0. Alphabetic character: if it is a non-z character, move one to the right, for example, d becomes e, G becomes H, if it is Z, Z - > A, z-a. Characters need to be kept in case,) non alphabetic characters such as', & ^ remain unchanged, and Chinese remains unchanged. Suggestion: use a Java file in the exercises learned before, such as circular exercises, there are many characters and numbers
package com.company; import java.io.*; public class TestStream { public static void encodeFile(File encodingFile, File encodedFile){ //encoding file encoded file char []all = new char[(int)encodingFile.length()]; try(FileReader fr = new FileReader(encodingFile)){ // Read all the contents of the file as a character stream fr.read(all); }catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } try (FileWriter fw = new FileWriter(encodedFile)){ for (int index = 0;index < all.length;index++){ if (Character.isLetter(all[index]) | Character.isDigit(all[index])) all[index] = encodeChar(all[index]); } fw.write(all); }catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } public static char encodeChar(char sourceChar){ char result = '\u0000'; int asciiNum = (int) sourceChar; // When the converted code is greater than 127, it can be judged that it is not ascii code and returned directly if (asciiNum > 127) return sourceChar; if (asciiNum >= 65 && asciiNum <= 90 || asciiNum >= 97 && asciiNum <= 122) { if (asciiNum >= 65 && asciiNum < 90 || asciiNum >= 97 && asciiNum < 122) return (char) (asciiNum + 1); else return (char)(asciiNum - 25); } return result; } public static void main(String[] args) { try { File encondingFile = new File("d:/lol.txt"); File encondedFile = new File("d:/lol.txt"); encodeFile(encondingFile,encondedFile); }catch (Exception e){ e.printStackTrace(); } } }
2.6 Chinese questions
-
Coding concept
The computer can only store numbers when storing data, and all characters will be converted into different numbers. Like a chessboard, different words are in different positions, and different positions have different numbers. Some chessboards are very small and can only put numbers and English; Some are bigger and can play Chinese; Some are "big enough" to put down all the words and symbols used by the people of the world.
As shown in the figure, the English character , A , can be placed on all chessboards, and the position is similar to that of the Chinese character. The Chinese character , A , can be placed on the latter two chessboards, and the position is different. Moreover, in the small chessboard, there is no Chinese character
-
Common coding
There are several coding methods frequently contacted after work: ISO-8859-1 ASCII number and Western European letter GBK GB2312 BIG5 Chinese UNICODE (unified code, universal code)
Among them, ISO-8859-1 contains ASCII, GB2312 is simplified Chinese, BIG5 is traditional Chinese, and GBK contains both simplified, traditional and Japanese. UNICODE includes all the characters, including Chinese, English, Tibetan, French and all the characters in the world
UNICODE and UTF
According to the previous study, we know that different coding methods correspond to different chessboards, and UNICODE has the largest chessboard because it needs to store all data. Moreover, each number in the chessboard is very long (4 bytes), because it should represent not only letters, but also Chinese characters.
If the data is stored completely according to UNICODE, it will be a great waste. For example, in ISO-8859-1, the number corresponding to a character is 0x61 and the number corresponding to UNICODE is 0x00000061. If most of an article is English letters, data saving in UNICODE will consume a lot of space
In this case, there are various weight loss sub codes of UNICODE. For example, UTF-8 uses one byte for numbers and letters and three bytes for Chinese characters, so as to achieve the effect of weight loss and health.
UTF-8, UTF-16 and UTF-32 have different weight loss effects for different types of data. Generally speaking, UTF-8 is a common way. The differences between UTF-8, UTF-16 and UTF-32 will not be repeated here. If you are interested, please refer to {unicode Baidu Encyclopedia
-
Java uses Unicode
Write in Chinese characters in java source code will become characters in JVM after execution. These Chinese characters are encoded in UNICODE The UNICODE corresponding to the word "Zhong" is 4E2D, so the data actually saved in memory is 0x4E2D in hexadecimal, that is, 20013 in decimal.
package stream; public class TestStream { public static void main(String[] args) { String str = "in"; } }
-
Expression of a Chinese character using different coding methods
Take the character , as an example to check its value under different coding methods, that is, its position on different chessboards
package stream; import java.io.UnsupportedEncodingException; public class TestStream { public static void main(String[] args) { String str = "in"; showCode(str); } private static void showCode(String str) { String[] encodes = { "BIG5", "GBK", "GB2312", "UTF-8", "UTF-16", "UTF-32" }; for (String encode : encodes) { showCode(str, encode); } //java learning and exchange: 737251827 enter to receive learning resources and ask questions about leaders with ten years of development experience for free! } private static void showCode(String str, String encode) { try { System.out.printf("character: \"%s\" In coding mode%s The hexadecimal value under is%n", str, encode); byte[] bs = str.getBytes(encode); for (byte b : bs) { int i = b&0xff; System.out.print(Integer.toHexString(i) + "\t"); } System.out.println(); System.out.println(); } catch (UnsupportedEncodingException e) { System.out.printf("UnsupportedEncodingException: %s The encoding method cannot resolve characters%s\n", encode, str); } } }
-
File encoding - Notepad
Next, save the characters in the file. The characters saved in the file must also be saved in the form of numbers, that is, corresponding to different numbers on different checkerboards, open any text file with notepad and save as. You can see a drop-down here. ANSI} This does not mean ASCII, but local coding. If you are a Chinese operating system, you will make GBK. If you are an English operating system, it will be ISO-8859-1
UNICODE , UNICODE native encoding , Unicode big endian , another UNICODE encoding , UTF-8 , the most common UTF-8 encoding, numbers and letters use one byte and Chinese characters use three bytes.
-
File encoding - eclipse
eclipse also has a similar encoding method. Right click any text file and click "property" at the bottom to see Text file encoding. There are also ISO-8859-1, GBK,UTF-8 and other options. Other US-ASCII,UTF-16, utf-16be and utf-16le are not commonly used.
-
In order to correctly read Chinese content
-
You must know in what encoding the text saves characters
-
After using the byte stream to read the text, use the corresponding encoding method to identify these numbers and get the correct characters
For example, if the content of a file is in characters and the encoding method is GBK, the read data must be D6D0. Then use GBK coding to recognize D6D0, and you can correctly get the information in the character
Note: after the Chinese character is found on the chessboard of GBK, the JVM will automatically find the corresponding number on the chessboard of UNICODE and save it in memory with the number on UNICODE.
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { File f = new File("E:\\project\\j2se\\src\\test.txt"); try (FileInputStream fis = new FileInputStream(f);) { byte[] all = new byte[(int) f.length()]; fis.read(all); //The data read out in the file is System.out.println("The data read out in the file is:"); for (byte b : all) { int i = b&0x000000ff; //Take only the last two hexadecimal digits System.out.println(Integer.toHexString(i)); } System.out.println("Put this number in GBK On your chessboard:"); String str = new String(all,"GBK"); System.out.println(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
-
Read Chinese correctly with FileReader character stream
FileReader gets characters, so it must have recognized bytes as characters according to some encoding, and the encoding method used by FileReader is charset If the return value of defaultcharset() is a Chinese operating system, it means that GBK FileReader cannot set the encoding method manually. In order to use other encoding methods, InputStreamReader can only be used instead, like this:
new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8"));
In this example, save Notepad as UTF-8 format, and then use UTF-8 to identify the corresponding Chinese.
Explanation: why is there one before the Chinese character? If the format of saving Notepad as UTF-8 is used, there is an identifier in the first byte, called BOM, to mark that the file is encoded in UTF-8.
package stream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; public class TestStream { public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException { File f = new File("E:\\project\\j2se\\src\\test.txt"); System.out.println("Default encoding method:"+Charset.defaultCharset()); //FileReader gets characters, so it must have recognized bytes as characters according to some coding //The encoding method used by FileReader is charset The return value of defaultcharset() is GBK if it is a Chinese operating system try (FileReader fr = new FileReader(f)) { char[] cs = new char[(int) f.length()]; fr.read(cs); System.out.printf("FileReader The default encoding method is used%s,The recognized characters are:%n",Charset.defaultCharset()); System.out.println(new String(cs)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //FileReader cannot set the encoding method manually. In order to use other encoding methods, InputStreamReader can only be used instead //And use new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8"); Such a form try (InputStreamReader isr = new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8"))) { char[] cs = new char[(int) f.length()]; isr.read(cs); System.out.printf("InputStreamReader Specify encoding method UTF-8,The recognized characters are:%n"); System.out.println(new String(cs)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
-
Exercise - Chinese corresponding to numbers
Find the three hexadecimal characters E5 B1 8C corresponding to UTF-8 coding
package stream; import java.io.UnsupportedEncodingException; public class TestStream { public static void main(String[] args) throws UnsupportedEncodingException { // Find the three hexadecimal characters E5 B1 8C corresponding to UTF-8 coding byte[] bs = new byte[3]; bs[0] = (byte) 0xE5; bs[1] = (byte) 0xB1; bs[2] = (byte) 0x8C; String str =new String(bs,"UTF-8"); System.out.println("E5 B1 8C The corresponding characters are:"+str); } }
-
Exercise - remove BOM
If you save Chinese characters in Notepad according to UTF-8 coding, a segment of identifier will be generated at the front, which is used to indicate that the file is encoded in UTF-8. Find out the hexadecimal corresponding to this identifier, and develop a method to automatically remove this identifier
package com.company; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; public class utf8Test { public static void main(String[] args) { File f = new File("d:\\lol.txt"); try(FileInputStream fis = new FileInputStream(f)){ byte[] all = new byte[(int) f.length()]; fis.read(all); System.out.println("First confirm according to UTF-8 What do you recognize?"); String str = new String(all,"UTF-8"); System.out.println(str); System.out.println("According to what I learned earlier, I know'in'Word corresponding UTF-8 The code is: e4 b8 ad"); System.out.println("The hexadecimal of all data in the printed file is:"); for (byte b : all){ int i = b&0xff; System.out.println(Integer.toHexString(i) + " "); } System.out.println(); System.out.println("Obtained by observation UTF-8 of BOM yes ef bb bf"); byte[] bom = new byte[3]; bom[0] = (byte) 0xef; bom[1] = (byte) 0xbb; bom[2] = (byte) 0xbf; byte[] fileContentWithoutBOM= removeBom(all,bom); System.out.println("Removed BOM The hexadecimal of the subsequent data is:"); for (byte b : fileContentWithoutBOM) { int i = b&0xff; System.out.print(Integer.toHexString(i)+ " "); } System.out.println(); System.out.println("The corresponding string has no question mark:"); String strWithoutBOM=new String(fileContentWithoutBOM,"UTF-8"); System.out.println(strWithoutBOM); }catch(IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static byte[] removeBom(byte[] all, byte[] bom) { return Arrays.copyOfRange(all, bom.length, all.length); } }
2.7 cache stream
Taking the hard disk as an example, the disadvantages of byte stream and character stream: the hard disk will be accessed every time you read and write. If the frequency of reading and writing is high, its performance is poor.
In order to solve the above disadvantages, cache stream is adopted: when the cache stream is read, it will read more data to the cache at one time. In the future, each reading is accessed in the cache until the data in the cache is read, and then read it to the hard disk.
When the cache stream writes data, it will first write the data to the cache until the cache reaches a certain amount, and then write these data to the hard disk together. According to this operation mode, the hard disk will not be accessed every byte written like byte stream and character stream, thus reducing IO operations
-
Read data using cache stream
BufferedReader can read one line of data at a time
package com.company; import java.io.*; import java.util.Arrays; public class utf8Test { public static void main(String[] args) { File f = new File("d:/lol.txt"); // Create file character stream // The cache stream must be based on 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(); } } }
-
Write out data using cache stream
PrintWriter caches the character output stream and can write out one line of data at a time
package stream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class TestStream { public static void main(String[] args) { // To file lol2 Txt File f = new File("d:/lol2.txt"); try ( // Create file character stream FileWriter fw = new FileWriter(f); // The cache stream must be based on an existing stream PrintWriter pw = new PrintWriter(fw); ) { pw.println("garen kill teemo"); pw.println("teemo revive after 1 minutes"); pw.println("teemo try to garen, but killed again"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
-
flush
Sometimes, you need to write data to the hard disk immediately instead of waiting until the cache is full. You need to use flush at this time
package stream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class TestStream { public static void main(String[] args) { //To file lol2 Txt File f =new File("d:/lol2.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("garen kill teemo"); //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("teemo revive after 1 minutes"); pw.flush(); pw.println("teemo try to garen, but killed again"); pw.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
-
Exercise - remove notes
Design a method to remove comments from Java files
public void removeComments(File javaFile)
For example, move out the comment line starting with / /
File f = new File("d:/LOLFolder/LOL.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());
package com.company; import java.io.*; import java.util.Arrays; public class utf8Test { public static void main(String[] args) { File f = new File("d:/lol.txt"); removeComments(f); } private static void removeComments(File javaFile){ try (FileReader fr = new FileReader(javaFile);BufferedReader br = new BufferedReader(fr)){ while(true){ String line = br.readLine(); if (null == line) break; if(line.startsWith("//")) continue; else System.out.println(line); } }catch (IOException e){ e.printStackTrace(); } } }
2.8 data flow
DataInputStream data input stream; DataOutputStream data output stream.
-
Read and write string directly
Use writeUTF() and readUTF() of the data stream to read and write the formatted data sequentially. For example, write Boolean values, integers and strings to the file sequentially through DataOutputStream. Then read these data in sequence through DataInputStream.
Note: to read a file with DataInputStream, the file must be written out by DataOutputStream, otherwise EOFException will occur, because DataOutputStream will make some special marks when writing out, and only DataInputStream can be read successfully.
package stream; import java.io.DataInputStream; import java.io.aDataOutputStream; 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:/lol.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:/lol.txt"); try ( FileOutputStream fos = new FileOutputStream(f); DataOutputStream dos =new DataOutputStream(fos); ){ dos.writeBoolean(true); dos.writeInt(300); dos.writeUTF("123 this is gareen"); } catch (IOException e) { e.printStackTrace(); } } }
2.9 object flow
Object streaming means that an object can be directly transmitted to other media in the form of streaming, such as hard disk.
An object is transmitted as a stream, which is called serialization. The class corresponding to the object must implement the Serializable interface.
-
Serialize an object
Create a Hero object and set its name to garen. Serialize the object into a file garen lol. The file is then converted into a Hero object by serialization
**Note: * * a precondition for serializing an object is that the class of this object must implement the Serializable interface
Hero.java
package charactor; import java.io.Serializable; public class Hero implements Serializable { //Indicates the current version of this class. If there are changes, such as newly designed attributes, this version number should be modified private static final long serialVersionUID = 1L; public String name; public float hp; }
TestStream.java
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import charactor.Hero; public class TestStream { public static void main(String[] args) { //Create a Hero garen //To save the Hero object directly to a file, make sure that the Hero class implements the Serializable interface Hero h = new Hero(); h.name = "garen"; h.hp = 616; //java learning and exchange: 737251827 enter to receive learning resources and ask questions about leaders with ten years of development experience for free! //Prepare a file to save the object File f =new File("d:/garen.lol"); try( //Create object output stream FileOutputStream fos = new FileOutputStream(f); ObjectOutputStream oos =new ObjectOutputStream(fos); //Create object input stream FileInputStream fis = new FileInputStream(f); ObjectInputStream ois =new ObjectInputStream(fis); ) { oos.writeObject(h); Hero h2 = (Hero) ois.readObject(); System.out.println(h2.name); System.out.println(h2.hp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2.10 System.in
System.out is commonly used to output data on the console; System.in can enter data from the console.
-
System.in
package stream; import java.io.IOException; import java.io.InputStream; public class TestStream { public static void main(String[] args) { // Console input try (InputStream is = System.in;) { while (true) { // You can see by typing in a and then typing back // 97 13 10 // 97 is the ASCII code of a // 13 and 10 correspond to carriage return and line feed respectively int i = is.read(); System.out.println(i); } } catch (IOException e) { e.printStackTrace(); } } }
-
Scanner reads string
package stream; import java.util.Scanner; public class TestStream { public static void main(String[] args) { Scanner s = new Scanner(System.in); while(true){ String line = s.nextLine(); System.out.println(line); } } }
Scanner reads integers from the console
package stream; import java.util.Scanner; public class TestStream { public static void main(String[] args) { Scanner s = new Scanner(System.in); int a = s.nextInt(); System.out.println("First integer:"+a); int b = s.nextInt(); System.out.println("Second integer:"+b); } }
-
2.11 comprehensive exercises
-
Copy file
Copying files is a common IO operation. The following method is designed to copy the source file srcFile to the target file destFile
public static void copyFile(String srcFile, String destFile){ }
-
Copy folder
Copy folder: copy all files in the source folder to the target folder (including subfolders) by the following methods
public static void copyFolder( String srcFolder, String destFolder){ }
-
Find file contents
public static void search( File folder, String search );
Suppose your project directory is e:/project, traverse all java files (including subfolders) in this directory, find out the files including Magic, and print them out.
2.12 flow diagram
-
Flow diagram
This figure is a simple arrangement of the flow relationships learned in this chapter
-
Stream is divided into byte stream and character stream
-
Data stream and object stream are commonly used under byte stream
-
There is also a cache stream commonly used under the character stream