File input and output stream
File Input and Output Stream FileInputStream and FileOutputStream are responsible for completing the sequential input and output operations of local disk files.
[Example] Create a file through a program, enter characters from the keyboard, end when the character "#" is encountered, and all the contents of the file are displayed on the screen
import java.io.*;class ep10_5{ public static void main(String args[]){ char ch; int data; try{ FileInputStream a=new FileInputStream(FileDescriptor .in); //Create file input stream object FileOutputStream b= new FileOutputStream("ep10_5"); //Create file output stream object System.out.println("Please enter the character and end with #:"); while((ch=(char)a.read())!= '#'){ b.write(ch); } a.close(); b.close(); System.out.println(); FileInputStream c=new FileInputStream("ep10_5"); FileOutputStream d=ne w FileOutputStream( FileDescriptor.out); while(c.available()>0){ data=c.read(); d.write(data); } c.close();d.close(); } catch(FileNotFoundException e) { System.out.println("This file cannot be found!"); } catch(IOException e){} }}
FileDescriptor is a class in java.io. This class cannot be instantiated and contains three static members: in, out and err, which correspond to standard input streams, standard output streams and standard error streams, respectively. They can be used to enter the standard input. Create a file input and output stream on the output stream to realize keyboard input or screen output operations.
[Example] Implement backup of binary graphics files (.gifs)
import java.io.*;class ep10_6{ public static void main(String args[]) throws IOException{ FileInputStream a=new FileInputStream("ep10_6.gif"); F ileOutputStream b=new FileOutputStream("ep10_6_a.gif"); System .out.println("The file size is: "+a.available()); byte c[]=new byte[a.available()]; a.read(c); //Read the graphics file into the array b.write(c); //Write the data in the array into a new file System.out.println("The file has been renamed and copied!"); a.close(); b.close(); }}
Filter flow
FilterInputStream and FileOutputStream are direct subclasses of InputStream and OutputStream. They respectively realize that while reading and writing data, they can convert the transmitted data in a specified type or format, so as to realize the understanding and encoding of binary byte data. Convert.
The two commonly used filtering streams are the data input stream DataInputStream and the data output stream DataOutputStream. Its construction method is:
DataInputStream(InputStream in); //Create a new input stream, read data from the specified input stream in DataOutputStream(OutputStream out); //Create a new output stream, write data to the specified output stream out
Since DataInputStream and DataOutputStream implement the formatted read and write operations defined in DataInput and DataOutput interfaces (the two interfaces specify the input and output methods of basic type data), the formatted read and write operations are realized for different types of data read and write. It can be seen from the construction method that the input and output streams are respectively used as construction methods parameters of the data input and output streams, that is, as filtered streams, they must be connected to the corresponding data streams.
The DataInputStream and DataOutputStream classes provide many reading and writing methods for different types of data. Readers can refer to the Java help document for specific content.
[Example] Write three int-type numbers 100, 0, and -100 to the data file ep10_6.dat.
import java.io.*;class ep10_7{ public static void main(String args[]){ String fileName="ep10_7.dat"; int value1=100,value2=0,value3=-1 00; try{ //Transfer DataOutputStream Connect to FileOutputStream to output different types of data DataOutputStream a=new DataOutputStream(new FileOutputStream(fileName)); a.writeInt(value1); a.writeInt(value2); a. writeInt(value3); a.close(); } catch (IOException i){ System.out.println("Error occurred!"+fileName); } }}
After running, generate the data file ep10_7.dat in the program directory. After opening it with a text editor, it is found that the content is binary:
00 00 00 64 00 00 00 00 FF FF FF 9C.
[Example] Read three int-type numbers in the data file ep10_6.dat, sum and display.
import java.io.*;class ep10_8{ public static void main(String args[]){ String fileName="D://myjava/ep10_7.dat"; int sum=0; try{ DataInput Stream a=new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); sum+=a.readInt(); sum+=a.readInt(); sum+=a.readInt(); System.out.println("The sum of three numbers is:" + sum); a.close(); } catch(IOException e){ System.out.println("Error occurred!" +fileName); } }}
Running results:
The sum of three numbers is: 0
The readInt method can read 4 bytes from the input and output stream and directly participate in the operation as int-type data. Since you already know that there are 3 data in the file, you can use 3 read-in statements, but what should you do if you only know that there is int-type data in the file but don’t know the number of data? Because if the read-in operation of DataInputStream is encountered, an EOFException will be thrown at the end of the file, the read operation can be put into the try.
try{ while(true) sum+=a.readInt();}catch(EOFException e){ System.out.pritnln("The sum of three numbers is: "+sum); a.close();}
EOFException is a subclass of IOException. It will only be caught when the file ends an exception. However, if the end of the file is not read, an exception occurs during the reading process will be an IOException.
[Example] Enter an integer from the keyboard and find the sum of the digits of the number.
import java.io.*;class ep10_9{ public static void main(String args[]) throws IOException{ DataInputStream a=new DataInputStream(System.in); System. out.print("Please enter an integer:"); int b=a.readInt(); int sum=0; int c=b; while(c>0){ int d=c%10; //Get the lowest bit c=c/10; //Remove the lowest bit sum= sum+d; //Accumulate the sum of all digits} The sum of all digits of System.out.println(b+"="+sum); }}
Running results:
Please enter an integer: 26842403082 The sum of the digits = 31
It should be noted that the input data 26 has become 842403082. The reason is that the input data does not conform to the format of the basic type of data. The data provided from the keyboard is the bytecode representation of characters. If 26 is input, it only represents 2 and 6. Two characters byte data, not byte code representing integer 26.
To get integers from the keyboard, you need to read the string first, and then use other methods to convert the string into integers.
Standard input and output
System.in, System.out, and System.err are defined in the java.lang.System package. These three objects will be automatically loaded when the Java source program is compiled.
Standard input: Standard input System.in is an object of the BufferedInputStream class. When the program needs to read data from the keyboard, it only needs to call the read() method of System.in, which reads a byte from the keyboard buffer. The binary data of , returns integer data with this byte as the low byte and the high byte as 0.
Standard Output: Standard Output System.out is an object of the PrintStream class PrintStream. The PrintStream class is a subclass of the filtered output stream class FilterOutputStream, which defines methods print() and println() that output different types of data to the screen.
Standard Error Output: System.err is used to display error messages to users and is also an error stream derived from the PrintStream class. The function of the Err stream is to make print() and println() output information to the err stream and display it on the screen for the convenience of users to use and debug programs.
[Example] Enter a string of characters to display it, and display the classes to which System.in and System.out belong.
import java.io.*;class ep10_10{ public static void main(String args[]){ try{ byte a[]=new byte[128]; //Set the input buffer System.out.print("Please enter characters String: "); int count =System.in.read(a); //Read the standard input and output stream System.out.println("Input is: "); for(int i=0;i<count; i++) System.out.print(a[i]+""); //Output the ASCII value of the array element System.out.println(); for(int i=0;i<count-2;i++) // Carriage return and line breaks are not displayed System.out.print((char)a[i]+""); //Output element System.out.println(); System.out.println("Input character The number is: "+count); Class InClass=System.in.getClass(); Class OutClass=System.out.getClass(); System.out.println("in The class where the item is: "+InClass.t oString( )); System.out.println("out The class where "out is: "+OutClass.toString()); } catch(IOException e){} }}
The running results are as follows:
It should be noted that after entering 3 characters and press Enter, the output result is displayed as 5 characters. This is because carriage return is treated as two characters in Java, one is a carriage return with ASCⅡ 13 and the other is a line break with a value of 10. In the program, getClass() and ToString() are methods of the Object class, which are respectively used to return the corresponding class to the current object and return the string representation of the current object.