The article [Java] [getting started] will help you understand java I/O

Posted by zoreli on Fri, 24 Dec 2021 23:19:31 +0100

In fact, it's not very difficult for java input and output. As long as you understand the input and output process, all you have to do is remember the class name

1, Leading:

Understand before you speak:

(1) : the input and output must be relative to the program---

a. what is the name of transferring data from the program to the other end? Called output

b. what is the name of transmitting data from the other end to the program? Well, it's called input

Understand this simple concept and go down

(2) : the other end of input / output, i.e. input / output end, is not just a file. As we will talk about, the keyboard and display screen are another input / output end

(3) : whether it is input to the program or output to the other end, there is a flow, which is equivalent to a transfer station. The data input and output are the first to arrive flow, which will be discussed later

2, All classes:

(1) Class that operates on File properties: File

(2) Classification of flow: (we are talking about classification by function)

a. node flow

Byte stream
                1,InputStream

                2,OutputStream  <------PrintStream

Character stream

                3,Reader

                4,Writer <-------PrintWriter

                5,ByteArrayInputStream

                6,ByteArrayOutputStream

b. processing flow

Buffer stream:

                1,BufferedOutputStream

                2,BufferedInputStream

                3,BufferedReader

                4,BufferedWriter

Conversion flow:

                5,OutputStreamReader

                6,InputStreamWriter

Data flow:

                7,DataInputStream

                8,DataOutputStream

Object flow:

                9,ObjectInputStream

                10,ObjectOutputStream

It can be seen from the above that there are not many input and output classes. You can understand that the following will focus on:

3, Analysis of specific classes

(1) File class

This class is actually an operation on file attributes, not the contents of the file. What does it mean?

That is, it can create, delete and obtain the size of files. Do these operations have any effect on the content??

It certainly doesn't. now I use the File class to read the File and input data to the File. Can this?? Obviously, you can't. is this a File read-write?? So you can understand this

So when it comes to files, what are the file systems?

a. Catalogue

b. Documents

These two, so the File class can create and delete these two, but the creation methods are different

example:

Operation on file:

public class Test {

	public static void main(String[] args) throws IOException {
		File file=new File("H:"+File.separator+"zdw.txt");
		
		file.createNewFile();//If it exists, you will not report an error if you create it again
		
		System.out.println(file.getPath());//Get relative path
		
		System.out.println(file.getAbsolutePath());//Get absolute path
		
		System.out.println(file.isFile());//Determine whether it is a file
		
		System.out.println(file.getName());//File name acquisition
		
		System.out.println(file.length());//Byte size of file contents
		
		file.delete();//Delete file
		
		System.out.println(file.exists());//Does not exist after deletion
	}

}

1. You can see that the relative path of the file and the absolute path of the file are the same. Why?

: because whose is the relative path? Relative to the folder where the project is located, and where is the project folder? In H:\Java\java\eclipse\workspace\testFiles, but the created files are in disk h, so they are not in the project directory. In this way, the natural relative path is the same as the absolute path

It must be understood that since it is a relative path, it must be relative to its own directory. Only when it is in its own directory, the relative path is not equal to the absolute path

2. You can see that after calling the delete () method, the file does not exist, and the input is false

Operation on Directory:

        

public class Test {

	public static void main(String[] args) {
		File file=new File("H:"+File.separator+"zdw");
		file.mkdir();//How to create a directory
		File file2=new File(file,"cn");//Instantiate the File class with the parent directory
		file2.mkdir();
		File file3=new File("H:/lyq/cn");
		file3.mkdirs();// If it is a multi-layer directory, the mkdir () method will not succeed
		System.out.println(file3.isDirectory());
		File file4=new File("H:/lyq");
		System.out.println(file4.isDirectory());
		System.out.println(file4.delete());	//Deleting a directory that is not empty will not report an error, but will not succeed
		//file3.delete();
		File file5=new File("H:/lyq/dn");
		File file6=new File("H:/lyq/bn");
		File file7=new File("H:/lyq/an");
		file5.mkdir();
		file6.mkdir();
		file7.mkdir();
		File file8=new File("H:/");
		String []strings=file8.list();
		for (String string : strings) {
			System.out.println(string);
		}
	}

}

In fact, for directory operations,

1. Its creation method is different from that of creating files. It is mkdir () and creates multi-layer directory mkdirs ()

2. You cannot delete a directory that is not empty. What do you mean? If there is a file or directory in my zdw directory, can I delete zdw directory successfully? The answer is No. how can I delete this zdw directory? Only delete everything in this directory!

3. In fact, this is mainly about the difference between the two methods

String [] list(): get the string of all directories and files under the directory

File [] listFiles(): what do you mean by getting the object of the directory or file under the directory instead of the string? Is that you can operate on these acquired things after acquisition. Why? Because you get the object!

Examples are as follows:

public class Test {

	public static void main(String[] args) throws IOException {
		File file5=new File("H:/lyq/dn");
		File file6=new File("H:/lyq/bn");
		File file7=new File("H:/lyq/an");
		file5.mkdir();
		file6.mkdir();
		file7.mkdir();
		File file8=new File(file5,"zdw.txt");
		file8.createNewFile();
		File file9=new File("H:/lyq");
		String []strings=file9.list();
		for (String string : strings) {
			System.out.println(string);
		}
		File[]files=file9.listFiles();
		files[2].delete();
	}

}

 

You can see:

1. Only the first level files or directories can be obtained

2. After it is obtained by the fileList() method, you can operate on the object, and you can see that cn the directory has been deleted

(2) Byte stream

        InputStream

        OutputStream

We can know from one that the target of input is not only files, but also keyboard, display screen, etc.. We will now analyze the documents. Others will be discussed later

example:

Let's first solve how to make the stream point to the file:

You can see that we used the subclasses FileInputStream and FileOutputStream of InputStream and OutputStream

Here, the write () method is to write an ascll code into the file. You can see that the file now has the character 'c'. Use the read () method of the input stream to read in an int type data. When outputting, it is output 99. It needs to be converted to output 'c';

Now let's look at the process of input and output:

public class Test2 {
	public static void main(String []zdw) throws IOException {
		File file=new File("H:/zdw.txt");
		file.createNewFile();
		InputStream inputStream=new FileInputStream(file);
		OutputStream outputStream=new FileOutputStream(file,false);//You can add a Boolean parameter,
//false means to overwrite the data in the file, while true means to continue adding after the data without overwriting!
		byte []b1= {99,100,101};
		byte []b2=new byte[2];
		outputStream.write(b1);//Read in a byte array
		int a=0;
		System.out.println(inputStream.available());//Get the data size in the stream at this time and output it
		while((a=inputStream.read(b2))!=-1) {
			System.out.println(inputStream.available());//
			System.out.println(new String(b2,0,a));//Output acquired data
		}
		System.out.println("last"+inputStream.read());//The last thing I read
		//inputStream.close();
		inputStream=new FileInputStream(file);
		System.out.println("again"+inputStream.read());
	}
}

You can see:

1. The input stream can be read into a byte array from the file (b2), and the output stream can output a byte array into the file (b1)

2. From the above explanation, why flow is a transfer station:

When the program runs, the data of the file is in the output stream. You can see that the size is 3. When an array is output, the size becomes 1 because "cd" is output, and finally becomes 0

3. The int value returned by the read () method represents the ascll code value of the read character

The int value returned by read (byte []) represents the size of the read data!

When reading to the end of the file, both methods return - 1, so you can use this feature to judge whether to read to the end of the file!

(3) Character stream

        Writer

        Reader

Why do we need character stream when we have byte stream? In fact, a simple reason is that in java, letters and Chinese characters are one character, and a Chinese character accounts for two bytes. It is incomplete to read with byte stream! Its knowledge points are roughly the same as those of byte stream, but the parameters are different

In the input stream, what read () returns is still the ascll value, while what read (char []) passes in is no longer a byte array, but a character array!

In the output stream, the writer (int) is also the ascll code for writing characters, and the writer (String) is no longer a byte array, but a String!

Instance: instantiate a file operation with its subclasses FileWriter and FileReader

1, you can see that after the write () method is used, the flush () method is invoked.

This is also one of the differences between character stream and byte stream. After the character stream is output, either flush() is used to brush the new stream or close() is used to close the stream, and the data will be sent to the file. Otherwise, it will not be sent

2. In the output, both sides are executed, because the size of the character array is 2, and there are 3 characters of data in the file, which also shows that the stream is a transit station!

3. Finally, it can be seen that there will be garbled code when reading Chinese characters with byte stream!

(4) Buffer stream

        BufferedInputStream

        BufferedOutputStream

        BufferedWriter

        BufferedReader

These streams are processing streams, that is, streams that need to use byte stream or character stream as parameter instantiation

Their function is to reduce the number of file accesses during input and output, so as to increase the operation efficiency of the program. In this way, it has a significant effect on the input and output of large files. It will not be demonstrated here

(5) Print stream

The parent class of PrintStream} class is OutputStream

The parent class of the printWriter} class is Writer

They have two methods, print (), and println ()

Their output targets can be displays or files

example

out is a static variable of the System class. Its type is PrintStream, so it can be instantiated. I will talk about it later. There is nothing else to talk about

(6) System class

There are three static variables in the System class:

1. out specifies that the output object is a screen} type is PrintStream

2. err specifies that the standard error output object is my screen, that is, the output is in red font and the output type is PrintStream

3. in specifies that the standard input object is the keyboard and obtains data from the keyboard into the program. The input type is InputStream

So we can know the system out. How did println () come from

Because what is the type of out? Is a PrintStream, so you can call its methods print() and println()

example:

We can see that because in is of InputStream type, it can only read bytes or byte arrays. As mentioned earlier, byte stream will be garbled when reading Chinese characters, so we need to use character stream. So what? This is the transformation flow we will talk about next!

(7) Conversion flow

        InputStreamWriter

        OutputStreamReader 

These two classes are processing streams. They need to instantiate them with byte streams as parameters

Their role is to transform bytes into character streams!

In (6), we encountered the problem of reading Chinese characters by System.in. Now we can solve the following problems:

You can see that the problem is solved. The conversion output stream is to program the byte output stream into the character output stream, which is omitted here!

(8) Scanner class

This class is actually quite familiar. We contacted it when we first learned java. It is used to input data from the keyboard, right

He has two construction methods,

One is to pass the File class: so this method is to input data from the File to the program

One is to pass the InputStream class: this method can input from the keyboard (passing in the System.in object) or file

example:

No demonstration from the keyboard

        

(9) Data flow

        DataInputStream

        DataOutputStream

These two are also processing streams, and byte streams are instantiated as parameters

Its function is to input and output basic type data instead of only processing characters as before

example:

        

It can be seen that although the code displayed in the file is garbled, it can still be read

But how to read it, you have to read it out. First output 22.3 double data to the above, and then output the string. If the input order is opposite, an error will be reported!

 

Because the data is finished when reading characters for the first time, and it is in the end when reading double type, so an error is reported!

(10) Object flow

        ObjectInputStream

        ObjectOutputStream

These are also processing streams

The function is to read in an object. We say that the data flow can only read in basic data types, so the object flow can be regarded as including data flow

To read in an object, the object must first have the function of serialization. Serialization means that the object can reach the destination in a binary way, and the basic data types implement this function. Therefore, when operating on a custom object, remember to implement this function, which is actually to implement the Serializable interface, just like a flag, No way to implement it!

example:

Person class: (operate on this kind of object)

public class Person implements Serializable{
	
	private String name;
	private  transient int   age;
	
	
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

 

public class Test {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		File file=new File("H:/person.bat");//. bat is an extended form of file, which can be written at will. It's ok if he's there
		Person person=new Person();
		person.setAge(19);
		person.setName("zdws");
		ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream(file));
		objectOutputStream.writeObject(person);//You can enter
		ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(file));
		person.setAge(20);
		person.setName("lyq");
		person=(Person) objectInputStream.readObject();
		System.out.println(person.getAge()+person.getName());
	}

}

You can see the successful input and output. The age is 0 because a transient modifier is added when defining the member variable. If you don't want to be seen, you can add this modifier!

Then there is another case. If I have saved such an object in it, but now I have changed the class of Person, do you think I can successfully read it? That's definitely not possible, so we need to add a jingtai constant to Person. The constant name is fixed as serialVersionUID, and its value is not fixed!

 

At this point, you can try to output to the file, then change the Person class, add a sex member variable for it, and then enter it to see whether it is successful. The answer is success!

(11) Byte array stream

        ByteArrayInputStream

        ByteArrayOutputStream

This class is not a processing stream, and it does not need to specify its input and output objects. Its function is to convert various data into byte array data. Why do you need this class

example:

         

Similarly, the order of output should be the same as that of input, because the flow body can be regarded as a queue!

In the above answer, the byte array stream is used to facilitate the transmission of data. If you want to transfer these messy data to one place, how do you use the object stream when transmitting on the network??? Therefore, we can only use the byte array stream, because the stream can turn these messy data into a byte array, so as long as we pass a byte array!

So far, that's all for java input and output. You can see that there are many classes, but will it be difficult to understand if these classes are taken out alone?

It certainly won't. In fact, as long as you understand the first three, it won't be difficult as a whole. More practice is the king. Bye, remember to press one button three times!!! Ha ha ha ha ha ha ha!!!

Topics: Java