The java.io package contains almost all the required classes for operation input and Output. All of these flow classes represent the input source and output Destination.
The streams in the Java.io package support many formats, such as basic types, objects, localized character sets, and so On.
A stream can be understood as a sequence of Data. The input stream represents reading data from one source, and the output stream represents writing data to a target.
Java provides powerful and flexible support for i/o, making it more widely available in file transfer and network Programming.
however, This article describes the most basic and current-to-i/o-related Features. We will learn these features through an example.
Read console input
Java console input is completed by System.in.
To get a character stream bound to the console, you can wrap the system.in in a BufferedReader object to create a character stream.
Here is the basic syntax for creating bufferedreader:
New BufferedReader (new inputstreamreader (system.in));
Once the BufferedReader object is created, we can use the Read () method to read a character from the console or to read a string with the ReadLine () method.
Read Multi-character input from the console
To read a character from a BufferedReader object to use the read () method, its syntax is as Follows:
int throws IOException
Each time the Read () method is called, it reads a character from the input stream and returns the character as an integer Value. Returns-1 when the stream ends. The method throws Ioexception.
The following program demonstrates the use of the Read () method to continuously read characters from the console until the user enters "q".
//using BufferedReader to read characters in the consoleImportJava.io.*; public classBrread { public Static voidMain (String Args[])throwsIOException {Charc; //Create BufferedReader using system.inBufferedReader br =NewBufferedReader (NewInputStreamReader (system.in)); System.out.println ("Enter characters, ' Q ' to quit."); //Read characters do{c= (Char) Br.read (); System.out.println (c); } while(c! = ' Q '); }}
The results of the above example compilation run as Follows:
Enter characters, ' Q ' to QUIT.123ABCQ123ABCQ
Reading a string from the console
Reading a string from standard input requires the use of the BufferedReader readline () method.
Its general format is:
throws IOException
The following program reads and displays the word lines until you enter the word "end".
//using BufferedReader to read characters in the consoleImportJava.io.*; public classBrreadlines { public Static voidMain (String Args[])throwsIOException {//Create BufferedReader using system.inBufferedReader br =NewBufferedReader (NewInputStreamReader (system.in)); String str; System.out.println ("Enter lines of text."); System.out.println ("Enter ' End ' to quit."); do{str=Br.readline (); System.out.println (str); } while(!str.equals ("end")); }}
The results of the above example compilation run as Follows:
Enter lines of Text. Enter ' End ' to Quit. This was line onethis are line onethis are line twothis are line twoendend
Console output
As already described earlier, the output of the console is done by print () and println (). These methods are defined by the class printstream, and System.out is a reference to the class Object.
PrintStream inherits the OutputStream class and implements the method write (). In this way, write () can also be used for writing to the Console.
The simplest format for the printstream definition of write () is as Follows:
void Write (int byteval)
This method writes the low eight-bit bytes of the byteval to the Stream.
Instance
The following example uses write () to output the character "A" and the immediately followed line break to the Screen:
import java.io.*; // Demo System.out.write (). public class Writedemo { publicstaticvoid main (String args[]) { int b; = ' A '; System.out.write (b); System.out.write (' \ n ');} }
Run the above instance output "A" character in Output window
A
note:The Write () method is not used frequently because the print () and println () methods are more convenient to Use.
Read and write files
As mentioned earlier, a stream is defined as a data series. The input stream is used to read data from the source, and the output stream is used to write data to the Target.
is a Class-level diagram that describes the input stream and the output Stream.
The two important streams that will be discussed below are FileInputStream and fileoutputstream:
FileInputStream
The stream is used to read data from a file, and its objects can be created with the keyword NEW.
There are several construction methods that you can use to create Objects.
You can use the file name of a string type to create an input stream object to read the File:
New FileInputStream ("c:/java/hello");
You can also use a file object to create an input stream object to read the File. We first have to use the file () method to create a document Object:
New File ("c:/java/hello"new FileInputStream (f);
When you create a inputstream object, you can use the following methods to read the stream or perform other flow operations.
Serial Number |
method and Description |
1 |
public void close () throws ioexception{} Closes this file input stream and frees all system resources related to this Stream. Throws a IOException Exception. |
2 |
protected void Finalize () throws IOException {} This method clears the connection to the File. Make sure that the Close method is called when the file input stream is no longer referenced. Throws a IOException Exception. |
3 |
public int Read (int R) throws ioexception{} This method reads the specified byte of data from the InputStream Object. Returns an integer Value. Returns the next byte of data, or 1 if it has reached the end. |
4 |
public int Read (byte[] R) throws ioexception{} This method reads bytes of r.length length from the input Stream. Returns the number of bytes Read. Returns 1 if it is the end of the File. |
5 |
public int available () throws ioexception{} Returns the number of bytes that the next method invoked on this input stream can be read from this input stream without blocking. Returns an integer Value. |
In addition to inputstream, there are some other input streams, more details refer to the following links:
- Bytearrayinputstream
- DataInputStream
FileOutputStream
This class is used to create a file and write data to the File.
If the stream does not exist before the file is opened for output, the stream creates the File.
There are two construction methods that you can use to create a fileoutputstream object.
Create an output stream object using the file name of the string type:
New
You can also use a file object to create an output stream to write a file. We first have to use the file () method to create a document Object:
New File ("c:/java/hello"new FileOutputStream (f);
Once the OutputStream object is created, you can use the following methods to write to the stream or perform other flow operations.
Serial Number |
method and Description |
1 |
public void close () throws ioexception{} Closes this file input stream and frees all system resources related to this Stream. Throws a IOException Exception. |
2 |
protected void Finalize () throws IOException {} This method clears the connection to the File. Make sure that the Close method is called when the file input stream is no longer referenced. Throws a IOException Exception. |
3 |
public void Write (int W) throws ioexception{} This method writes the specified bytes to the output Stream. |
4 |
public void Write (byte[] W) Writes bytes of w.length length in the specified array to Outputstream. |
In addition to the outputstream, there are some other output streams, more details refer to the following links:
- Bytearrayoutputstream
- DataOutputStream
Instance
Here is an example demonstrating the usage of InputStream and outputstream:
ImportJava.io.*; public classfilestreamtest{ public Static voidmain (String Args[]) {Try{ byteBwrite [] = {11,21,3,40,5}; OutputStream OS=NewFileOutputStream ("test.txt"); for(intx=0; X < bwrite.length; X + +) {os.write (bwrite[x]);//writes the bytes} os.close (); InputStream is=NewFileInputStream ("test.txt"); intSize =is.available (); for(inti=0; i< size; i++) {System.out.print (Char) Is.read () + ""); } is.close (); }Catch(ioexception e) {System.out.print ("Exception"); } }}
The above program first creates the file Test.txt and writes the given number in binary form into the file and outputs it to the Console.
The above code is written by the binary, there may be garbled, you can use the following code example to solve the garbled problem:
//file name: Filestreamtest2.javaImportJava.io.*; public classfilestreamtest2{ public Static voidMain (string[] Args)throwsIOException {File F=NewFile ("a.txt"); FileOutputStream FOP=NewFileOutputStream (f); //Build FileOutputStream object, file does not exist automatically newOutputStreamWriter writer=NewOutputStreamWriter (fop, "UTF-8"); //build the OutputStreamWriter object, parameters can specify the encoding, default is the operating system default encoding, Windows is GBKWriter.append ("chinese input"); //Write to BufferWriter.append ("\ r \ n"); //line BreakWriter.append ("中文版"); //Flush Cache punch, write to file, if no content is written below, direct close also writesWriter.close (); //the write stream is closed and the buffer contents are written to the file, so the comment aboveFop.close (); //turn off the output stream and release system resourcesFileInputStream FIP=NewFileInputStream (f); //Building FileInputStream ObjectsInputStreamReader Reader=NewInputStreamReader (fip, "UTF-8"); //build the InputStreamReader object with the same encoding as the writeStringBuffer SB=NewStringBuffer (); while(reader.ready ()) {sb.append (Char) Reader.read ()); //go to char and add to StringBuffer object} System.out.println (sb.tostring ()); Reader.close (); //turn off Read streamFip.close (); //close the input stream and release system resources }}
File and I/O
There are also classes about files and i/o, and we need to know:
- File class (class)
- FileReader class (class)
- FileWriter class (class)
Directory creation directory in Java:
There are two methods in the file class that can be used to create a folder:
- the mkdir () method creates a folder, returns True if successful, and returns false if it Fails. Failure indicates that the path specified by the file object already exists, or that the folder cannot be created because the entire path does not yet Exist.
- the mkdirs () method creates a folder and all its parent folders.
The following example creates the "/tmp/user/java/bin" folder:
Import java.io.File; public class createdir { publicstaticvoid main (String args[]) { = "/tmp/ User/java/bin "; New File (dirname); // Create directory now d.mkdirs (); }}
Compile and execute the above code to create the directory "/tmp/user/java/bin".
note: Java automatically distinguishes file path delimiters by convention in Unix and Windows. If you use the delimiter (/) in the Windows version of java, the path can still be parsed correctly.
Read Directory
A directory is actually a file object that contains other files and Folders.
If you create a file object and it is a directory, then calling the Isdirectory () method returns True.
You can extract a list of the files and folders it contains by calling the list () method on the Object.
The example shown below shows how to use the list () method to check what is contained in a folder:
Importjava.io.File; public classDirlist { public Static voidmain (string args[]) {string dirname= "/tmp"; File F1=NewFile (dirname); if(f1.isdirectory ()) {System.out.println ("Directory of" +dirname); String s[]=f1.list (); for(inti=0; I < s.length; i++) {File F=NewFile (dirname + "/" +s[i]); if(f.isdirectory ()) {System.out.println (s[i)+ "is a directory"); } Else{System.out.println (s[i]+ "is a file"); } } } Else{System.out.println (dirname+ "is not a directory"); } }}
The results of the above example compilation run as Follows:
Directory Of/tmpbin is a directorylib is a directorydemo are a directorytest.txt is a filereadme are a fileindex.html is a Fileinclude is a directory
Java stream (stream), file, and IO