www.runoob.com/java/java-f…
The java.io package contains almost all the classes needed for input and output of operations. All of these stream classes represent input sources and output targets.
Streams in the java.io package support many formats, such as primitive types, objects, localized character sets, and so on.
A stream can be thought of as a sequence of data. The input stream represents reading data from a source and the output stream represents writing data to a target.
Java provides powerful and flexible support for I/O, making it more widely used in file transfer and network programming.
But this section covers the most basic I/ O-related functions of streams. We’ll look at each of these features by example.
Read console input
Java’s console input is done by System.in.
To get a character stream bound to the console, you can wrap system. in a BufferedReader object to create a character stream.
Here is the basic syntax for creating a BufferedReader:
package object.inputSystem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Systemin { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); }}Copy the code
Once the BufferedReader object is created, we can use the read() method to read a character from the console or the readLine() method to read a string.
Read multi-character input from the console
To read a character from a BufferedReader object, use the read() method, which has the following syntax:
int read( ) throws IOException
Copy the code
Each time the read() method is called, it reads a character from the input stream and returns that character as an integer value. Returns -1 when the stream ends. This method throws an IOException.
Class: Tt
package object.inputSystem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Systemin { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); int read = bufferedReader.read(); System.out.println(read); }}Copy the code
The Console:
A
65
Copy the code
Class: BRRead
package object.inputSystem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BRRead { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); int c = -1; while((c = bufferedReader.read()) ! = -1){ System.out.println((char)c); if((char)c == 'q') break; }}}Copy the code
The Console:
lime
l
i
m
e
q
q
Copy the code
Reads the string from the console
Reading a string from standard input requires the BufferedReader’s readLine() method.
Its general format is:
String readLine( ) throws IOException
Copy the code
Class: Tt
package object.inputSystem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Systemin { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String read = bufferedReader.readLine(); System.out.println(read); }}Copy the code
The Console:
ABCD
ABCD
Copy the code
Class : BRReadLines
package object.inputSystem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BRReadLines { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String readLine = ""; while(! (readLine = bufferedReader.readLine()).equals("end")){ System.out.println(readLine); }}}Copy the code
Console :
lime
lime
Oracle
Oracle
end
Copy the code
Since JDK 5 we can also use the Java Scanner class to get input from the console.
Console output
As described earlier, the console output is done by print() and println(). These methods are defined by the class PrintStream, to which System.out is a reference.
PrintStream inherits the OutputStream class and implements the method write(). Thus, write() can also be written to the inbound console.
PrintStream defines write() in its simplest form as follows:
void write(int byteval)
Copy the code
This method writes the lower octet of byteVal to the stream.
Class: WriteDemo
package object.outputSystem; public class WriteDemo { public static void main(String[] args) { // A = 65 = B0100 0001 int b = 'A'; System.out.write(b); System.out.write('\n'); // 0x41 = B0100 0001 byte bt = (byte)0x41; System.out.write(bt); System.out.write('\n'); // 321 = B0001 0100 0001 int bigger = 321; System.out.write(bigger); System.out.write('\n'); }}Copy the code
Console :
A
A
A
Copy the code
Note: The write() method is not often used because the print() and println() methods are more convenient to use.
Read and write files
As mentioned earlier, a stream is defined as a sequence of data. The input stream is used to read data from the source and the output stream is used to write data to the destination.
The following diagram is a class hierarchy diagram describing input and output streams.
TXT:
Object
:InputStream
:FileInputStream
:OutputStream
:FileOutputStream
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
:ByteArrayInputStream
:ByteArrayOutputStream
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
:FilterInputStream
:BufferedInputStream
:DataInputStream
:PushbackInputStream
:FilterOutputStream
:BufferedOutputStream
:DataOutputStream
:PrintStream
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
:StringBufferInputStream
:SequenceInputStream
Copy the code
Two important streams are FileInputStream and FileOutputStream:
FileInputStream
This stream is used to read data from a file, and its objects can be created with the keyword new.
There are several constructors available to create objects.
We can use a string filename to create an input stream object to read the file:
InputStream f = new FileInputStream("F:/java/hello");
Copy the code
You can also use a file object to create an input stream object to read the file. We first have to create a File object using the File() method:
File f = new File("F:/java/hello");
InputStream f = new FileInputStream(f);
Copy the code
Once you have created the InputStream object, you can use the following methods to read the stream or perform other stream operations.
⊙ public void close() throws IOException{}: Closes the file input stream and releases all system resources related to the stream. Throws IOException.
⊙ Protected void Finalize ()throws IOException {} : This method clears the connection to the file. Ensure that the file input stream’s close method is called when it is no longer referenced. Throws IOException.
⊙ Public int read(int r)throws IOException{} : This method reads the specified byte of data from an InputStream. Returns an integer value. Returns the next byte of data, or -1 if it has reached the end.
⊙ Public int read(byte[] r) throws IOException{} : This method reads R. length bytes from the input stream. Returns the number of bytes read. Returns -1 if it is the end of the file.
⊙ Public int Available () throws IOException{} : Returns the number of bytes that can be read from this input stream without blocking the next time a method is called on this input stream. Returns an integer value.
In addition to InputStream, there are several other input streams. See the links below for more details:
- ByteArrayInputStream
- DataInputStream
FileOutputStream
This class is used to create and write data to a file.
If the target file does not exist before the stream opens the file for output, the stream creates the file.
There are two constructors you can use to create FileOutputStream objects.
Create an output stream object with a filename of type string:
OutputStream f = new FileOutputStream("F:/java/hello")
Copy the code
You can also use a file object to create an output stream to write files. We first have to create a File object using the File() method:
File f = new File("F:/java/hello");
OutputStream f = new FileOutputStream(f);
Copy the code
Once you have created an OutputStream object, you can use the following methods to write to the stream or perform other stream operations.
⊙ public void close() throws IOException{} : Closes the file input stream and releases all system resources related to the stream. Throws IOException.
⊙ Protected void Finalize ()throws IOException {} : This method clears the connection to the file. Ensure that the file input stream’s close method is called when it is no longer referenced. Throws IOException.
⊙ Protected void Finalize ()throws IOException {} : This method clears the connection to the file. Ensure that the file input stream’s close method is called when it is no longer referenced. Throws IOException.
⊙ Public void write(byte[] w) : Writes w.length bytes from the specified array to an OutputStream.
In addition to outputStreams, there are several other output streams. See the links below for more details:
- ByteArrayOutputStream
- DataOutputStream
Class: FileStreamTest
package object.Stream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileStreamTest { public static void main(String[] args) throws IOException { byte[] bWrite = { 11, 21, 3, 40, 5}; FileOutputStream fileOutputStream = new FileOutputStream("Tt.txt"); for(int i = 0; i < bWrite.length; i++){ fileOutputStream.write(bWrite[i]); } fileOutputStream.close(); // -- -- -- -- -- -- -- -- -- FileInputStream fileInputStream = new FileInputStream("Tt.txt"); int available = fileInputStream.available(); for(int i = 0; i < available; i++){ System.out.print((char)fileInputStream.read() + " "); } fileInputStream.close(); }}Copy the code
The Console:
The Result:
Because the above code is written in binary, there may be garbled characters, you can use the following code example to solve the garbled problem:
Class: FileStreamReaderWriter
package object.Stream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class FileStreamReaderWriter { public static void main(String[] args) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream("Tt.txt"); GBK OutputStreamWriter OutputStreamWriter = new on Windows OutputStreamWriter(fileOutputStream, "UTF-8"); / / written to the buffer outputStreamWriter. Append (", "Chinese input), append (" \ r \ n"), append (" like circuit and display \ n \ n you only contact me flank with look like \ n you know I'm the face \ n you know me? Do you understand me? \n").append("lime"); Flush outputStreamWriter.flush(); flush outputStreamWriter.flush(); outputStreamWriter.append("Can you blow my whistle baby, whistle baby?" ); Flush outputStreamWriter.close(); flush outputStreamWriter.close(); flush outputStreamWriter.close(); Fileoutputstream.close (); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- FileInputStream fileInputStream = new FileInputStream("Tt.txt"); InputStreamReader = new InputStreamReader(fileInputStream,"UTF-8"); StringBuffer stringBuffer = new StringBuffer(); // Ready is a non-blocking method to see if the stream is ready to be read, so it returns immediately. while(! inputStreamReader.ready()){ System.out.println("not ready"); } while(inputStreamReader.ready()){ stringBuffer.append((char)inputStreamReader.read()); } System.out.println(stringBuffer.toString()); fileInputStream.close(); inputStreamReader.close(); }}Copy the code
File and I/O
There are also some files and I/O classes we need to know about:
- The File Class (Class)
- FileReader Class (Class)
- FileWriter Class (Class)
Directories in Java
Create a directory:
The File class has two methods for creating folders:
- The mkdir() method creates a folder, returning true on success and false on failure. 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 of its parent folders.
Class : CreateDir
package object.file; import java.io.File; public class CreateDir { public static void main(String[] args) { File file = new File("F:/Tt/TtSubDir/limeDir/OracleDir"); boolean mkdir = file.mkdir(); if (! Mkdir) {system.out.println (" file creation failed "); boolean mkdirs = file.mkdirs(); If (mkdirs) {system.out.println (" file created successfully "); }}}}Copy the code
Console :
Failed to create a file. Succeeded in creating a fileCopy the code
Read the directory
A directory is simply a File object that contains other files and folders.
If a File object is created and it is a directory, calling isDirectory() returns true.
You can extract a list of files and folders it contains by calling the list() method on the object.
Class : DirList
package object.file; import java.io.File; public class DirList { public static void main(String[] args) { String dirname = "F:/Tt"; File file = new File(dirname); if(file.isDirectory()){ String path = file.getPath(); System.out.println(" directory: "+ path); String[] list = file.list(); for(String str : list){ File fl = new File(path + File.separator + str); if(fl.isDirectory()){ System.out.println(str + " is Directory"); }else{ System.out.println(str + " is File"); } } }else{ System.out.println(file.getName() + " is not Directory"); }}}Copy the code
Console :
F:\Tt TtSubDir is DirectoryCopy the code
Delete a directory or file
Files can be deleted using the java.io.file.delete () method.
The following code will delete the directory F:\Tt\TtSubDir\limeDir\OracleDir\ tt.txt, even if the directory is not empty.
package object.file; import java.io.File; Public class DeleteFileDemo {public static void main(String args[]) {File Folder = new File("F:/Tt"); deleteFolder(folder); } // Delete files and directories public static void deleteFolder(File Folder) {File[] files = folder.listfiles (); if (files ! = null) { for (File f : files) { if (f.isDirectory()) { deleteFolder(f); } else { f.delete(); } } } folder.delete(); }}Copy the code