java IO learning
Concept of flow
It is a channel that transfers data between memory and storage devices
Classification of flow
-
By unit:
-
Byte stream, you can input any data, because any data is stored in bytes in memory
-
Character stream can only read data in text form, because some characters are one byte, two bytes and three bytes
-
-
By function:
- The node stream, also known as the underlying stream, has the function of reading and writing the actual transmission data
- Buffer stream, an enhancement implemented only on node stream
Byte stream learning
Parent class (abstract class) of byte stream input: InputStream and OutputStream respectively
//Use the subclass [FileInputStream,FileOutputStream] of these two abstract classes to read and write files //Copy files public class FileCopy { public static void main(String[] args) throws Exception { FileInputStream in = new FileInputStream("d:\\1.png"); FileOutputStream out = new FileOutputStream("d:\\2.png"); byte[] buffer = new byte[1024]; //Byte here cannot be byte int count=0; while((count=in.read(buffer))!=-1){ out.write(buffer,0,count); //count outputs the number of read bytes } in.close(); //Remember to close the flow after use out.close(); } }
Buffer flow learning
- Buffer streams BufferedInputStream and BufferedOutputStream actually add an 8K buffer inside the class. Each read and write will be put into the buffer first, which improves IO efficiency
//File reading with BufferedInputStream public class MyBufferdInput { public static void main(String[] args) throws Exception { //Note that an underlying InputStream object needs to be placed here BufferedInputStream bin = new BufferedInputStream(new FileInputStream("d:\\hello.txt")); int data=0; while((data=bin.read())!=-1){ System.out.print((char)data); } bin.close(); } }
//Realizing file write out with BufferedOutputStream public class MyBufferdInput { public static void main(String[] args) throws Exception { //Note that an underlying OutputStream object [node stream] needs to be placed here BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("d:\\helloout.txt")); int data=0; String s = "hello"; for (int i = 0; i < 10; i++) { bout.write(s.getBytes()); bout.flush(); //This code means to write the contents to the disk without writing to the buffer once, and do not wait until it is full 8k } bout.close(); //If there is no refresh above, it will also be written out to disk } }
Object flow
- Writing / reading objects using streams is called serialization / deserialization
- matters needing attention:
- Serialized classes must implement the Serializable interface
- The Serializable interface also needs to be implemented for the object properties in the serialization class
- Static properties cannot be serialized
- If the attribute in the class is added with transient, it cannot be serialized
- If you want to serialize multiple objects at the same time, you can serialize them with a collection such as list
public class Serialize { public static void main(String[] args) throws Exception{ //Serialization. Note that the underlying stream object is required here ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("d:\\stu.txt")); Student stu1 = new Student("Zhang San", 18); Student stu2 = new Student("Li Si", 22); //out.writeObject(stu); List<Student> list = new ArrayList<>(); list.add(stu1); list.add(stu2); out.writeObject(list); //Serialize a linked list out.close(); System.out.println("Serialization succeeded"); //Deserialization ObjectInputStream in = new ObjectInputStream(new FileInputStream("d://stu.txt")); //Object returnstu=in.readObject(); ArrayList<Student> returnStu= (ArrayList<Student>) in.readObject(); in.close(); System.out.println(returnStu.toString()); } } class Student implements Serializable { private String name; private int age; public static int id; //These two properties cannot be serialized public transient char sex; public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } } //output Serialization succeeded [Student{name='Zhang San', age=18}, Student{name='Li Si', age=22}]
Character stream
- Common character codes: utf-8, gbk
- Because there will be problems in reading Chinese characters in byte stream, there are Reader and Writer (parent class and abstract class)
//Use of FileReader and FileWriter: in fact, the usage is the same as that of FileInputStream and FileOutputStream above public class FileReaderAndFileWriter { public static void main(String[] args) throws Exception{ //Write Chinese characters to file FileWriter fw = new FileWriter("d://filewrite.txt"); for (int i = 0; i < 5; i++) { fw.write("Hello world\r\n"); } fw.close(); FileReader fr = new FileReader("d://filewrite.txt"); int data=0; while ((data = fr.read()) != -1) { System.out.print((char)data); } } }
Character buffer stream
- One line can be read
//Use of BufferReader and BufferWriter: it is basically no different from the byte buffer stream above public class BufferedReaderAndBufferedWriter { public static void main(String[] args) throws Exception { BufferedWriter bw = new BufferedWriter(new FileWriter("d://bw.txt")); for (int i = 0; i < 5; i++) { bw.write("study hard and make progress every day"); bw.newLine(); //The function is \ r\n (line feed) } bw.close(); //Close flow System.out.println("Write successful"); BufferedReader br = new BufferedReader(new FileReader("d://bw.txt")); String ans=null; while((ans=br.readLine())!=null){ //It can be read line by line System.out.println(ans); } br.close(); //Close flow } }
Conversion flow
- The difference between the conversion of bytes in the hard disk and characters in the memory is that the encoding method can be specified when reading and writing
//Use of OutputStreamWriter and InputStreamReader public class InputStreamWriter { public static void main(String[] args) throws Exception{ //Write the file to the file in utf-8 format OutputStreamWriter osw = new OutputStreamWriter(//Note that the underlying flow is also required here new FileOutputStream("d://osw.txt"), "utf-8"); for (int i = 0; i < 5; i++) { osw.write("Hello, world\r\n"); } osw.close(); System.out.println("Output successful"); //The file must also be read out in utf-8 gbk -- corresponding to ANSI InputStreamReader isr = new InputStreamReader( new FileInputStream("d://osw.txt"),"utf-8 "/ / note that if you read it here in gbk //It's garbled ); int data=0; while ((data = isr.read()) != -1) { System.out.print((char)data); } } }
Operation of files and folders
basic operation
public class MyFile { public static void main(String[] args) throws Exception { //Separator System.out.println(File.pathSeparator); //Path separator; System.out.println(File.separator); //Name separator\ File file = new File("d://a.txt"); //create a file if (!file.exists()){ file.createNewFile(); } //Delete file /*file.delete();*/ //Get file information System.out.println(file.getName()); //file name System.out.println(file.length()); //Number of bytes occupied by the file System.out.println(file.getPath()); //Path to file System.out.println(file.isFile()); //Is it a file System.out.println(file.canWrite()); //Is the file writable } } //Folder operation //The difference from the above is that you can create folders and traverse folders [with list] file.makedir //Create a single level directory fiel.makedirs //Create multi-level directory
File filtering
//Filter out the folder with suffix png file public class FIleFilter { public static void main(String[] args) { File dir = new File("d:files"); File[] files=dir.listFiles(new FileFilter() { //Implement the FileFilter interface by anonymous inner class @Override public boolean accept(File pathname) { if (pathname.getName().endsWith(".png")) { //The suffix is filtered out png file return true; } else { return false; } } }); for (File file:files) { System.out.println(file.getPath()); } } }
File traversal
//Recursively traverse folders public class FilePrint { public static void main(String[] args) { printDir(new File("d://files")); } public static void printDir(File dir) { File[] files = dir.listFiles(); //As long as you traverse, you need to use the collection for (File file:files) { if (file.isFile()) { System.out.println(file.getPath()); //Simple recursion } else { printDir(file); } } } }
Use of stream related collection properties
public class Propertirs { public static void main(String[] args) throws Exception{ Properties pro = new Properties(); pro.setProperty("Zhang San", "18"); //Note: the key and value in properties are of String type pro.setProperty("Li Si", "Beijing"); Set<String> pros=pro.stringPropertyNames(); for (String s:pros) { System.out.println(s+pro.getProperty(s)); } //Output a collection to a file through a stream /*PrintWriter out=new PrintWriter("d://pro.properties"); pro.list(out); out.close();*/ //Output to the stream through store OutputStream out = new FileOutputStream("d://properties"); pro.store(out,"what"); out.close(); //Read the stream through load Properties pro2 = new Properties(); FileInputStream in = new FileInputStream("d://properties"); pro2.load(in); in.close(); System.out.println(pro2.toString()); } }