The Java.io package contains almost all the classes needed to manipulate input and output. All of these stream classes represent input sources and output targets.
Streams in the Java.io package support a variety of 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 destination.
Java provides powerful and flexible support for I/O, making it more widely used in file transfer and network programming.
However, this section describes the most basic functions related to streaming and I/O. We will learn these functions through an example.
Reading console input
Java's console input is done by System.in.
To get a stream of characters bound to the console, you can wrap System.in in a BufferedReader object to create a stream of characters.
Here is the basic syntax for creating a BufferedReader:
BufferedReader br = new BufferedReader ( new InputStreamReader ( System . in ) ) ;
After the BufferedReader object is created, we can use the read() method to read a character from the console, or read a string using the readLine() method.
Read multiple character input from the console
Reading a character from a BufferedReader object uses the read() method, which has the following syntax:
Int read ( ) 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. This method throws an IOException.
The following program demonstrates using the read() method to continuously read characters from the console until the user enters "q".
BRRead.java file code:
// Use the BufferedReader to read characters on the console
import java.io.*;
public class BRRead {
public static void main(String args[]) throws IOException
{
char c;
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println(" Enter the character, press the 'q' key to exit. ");
// Read the character
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
The above example compiled and run results are as follows:
Enter the character and press 'q' to exit. bubble b u b b l e q q
Reading strings from the console
Reading a string from standard input requires using the BufferedReader's readLine() method.
Its general format is:
String readLine ( ) throws IOException
The following program reads and displays character lines until you enter the word "end".
BRReadLines.java file code:
// Use the BufferedReader to read characters on the console
import java.io.*;
public class BRReadLines {
public static void main(String args[]) throws IOException
{
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(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 above example compiled and run results are as follows:
Enter lines of text. Enter 'end' to quit. This is line one This is line one This is line two This is line two end end
After JDK 5 we can also use the Java Scanner class to get console input.
Console output
As mentioned earlier, the console output is done by print( ) and println( ). These methods are defined by the class PrintStream, a reference to the class object.
PrintStream inherits the OutputStream class and implements the method write(). In this way, write() can also be used to write to the console.
The simplest form of PrintStream definition for write() is as follows:
Void write ( int byteval )
This method writes the lower octet of byteval into the stream.
Examples
The following example uses write() to output the character "A" followed by a newline character to the screen:
WriteDemo.java file code:
import java.io.*;
// Demonstrates System.out.write().
public class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
Run the above example to output the "A" character in the output window
A
Note: The write() method is not used often 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 sequence. The input stream is used to read data from the source, and the output stream is used to write data to the target.
The following figure is a class hierarchy diagram that describes the input stream and the output stream.

FileInputStream
The stream is used to read data from a file, its objects can be created with the keyword new.
There are several constructors that can be used to create objects.
You can use string-type file names to create an input stream object to read the file:
InputStream f = new FileInputStream ( " C:/java/hello " ) ;
You can also use a file object to create an input stream object to read the file. We first need to use the File() method to create a file object:
File f = new File ( " C:/java/hello " ) ;
InputStream out = new FileInputStream ( f ) ;
Create an InputStream object, you can use the following method to read the stream or perform other stream operations.
No. | Method and description |
---|---|
1 | Public void close() throws IOException{} Closes this file input stream and releases any system resources associated with this stream. Throws IOException. |
2 | Protected void finalize() throws IOException {} This method clears the connection to the file. Make sure to call its close method when it no longer references the file input stream. Throws IOException. |
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 length r.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 can be read from this input stream unblocked by the next call to this input stream method. Returns an integer value. |
In addition to InputStream, there are other input streams. For 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 export, the stream creates the file.
There are two constructors that can be used to create a FileOutputStream object.
Create an output stream object using a string-type file name:
OutputStream f = new FileOutputStream ( " C:/java/hello " )
You can also use a file object to create an output stream to write a file. We first need to create a file object using the File() method:
File f = new File ( " C:/java/hello " ) ;
OutputStream f = new FileOutputStream ( f ) ;
After creating the OutputStream object, you can use the following methods to write the stream or perform other stream operations.
No. | Method and description |
---|---|
1 | Public void close() throws IOException{} Closes this file input stream and releases any system resources associated with this stream. Throws IOException. |
2 | Protected void finalize() throws IOException {} This method clears the connection to the file. Make sure to call its close method when it no longer references the file input stream. Throws IOException. |
3 | Public void write(int w) throws IOException{} This method writes the specified byte to the output stream. |
4 | Public void write(byte[] w) Writes the length of w.length in the specified array to the OutputStream. |
In addition to OutputStream, there are some other output streams. For more details, refer to the following links:
- ByteArrayOutputStream
- DataOutputStream
Examples
Here is an example that demonstrates the usage of InputStream and OutputStream:
fileStreamTest.java file code:
import java.io.*;
public class fileStreamTest{
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=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 into the file in binary form and outputs it to the console.
Since the above code is written in binary and may be garbled, you can use the following code example to solve the garbled problem:
fileStreamTest2.java file code:
// File name: fileStreamTest2.java
import java . io .*;
public class fileStreamTest2 {
public static void main ( String [ ] args ) throws IOException {
File f = new File ( " a.txt " ) ; FileOutputStream fop = new FileOutputStream ( f ) ;
// Build FileOutputStream Object, file does not exist will be automatically created OutputStreamWriter writer = new OutputStreamWriter ( fop , " UTF-8 " ) ;
// Build OutputStreamWriter object, parameters can specify the encoding, the default is the operating system default encoding, windows is gbk Writer . append ( " Chinese input " ) ; // write to buffer Writer . append ( " \r \n " ) ; // Line feed Writer . append ( " English " ) ; // Refresh cache flush, write to file, if there is no content written below, direct close will also write Writer . close ( ) ; // Closes the write stream and writes the contents of the buffer to the file, so the comment above is fop . close ( ) ; // Close output stream and release system resources FileInputStream fip = new FileInputStream ( f ) ; // Build a FileInputStream object InputStreamReader reader = new InputStreamReader ( fip , " UTF-8 " ) ; // Build InputStreamReader object, same as encoding and writing StringBuffer sb = new StringBuffer ( ) ; while ( reader . ready ( ) ) {
sb . append ( ( char ) reader . read ( ) ) ; // convert to char added to StringBuffer object }
System . out . println ( sb . toString ( ) ) ; reader . close ( ) ; // Close the read stream fip . close ( ) ; // Close the input stream and release system resources }
}
public static void main ( String [ ] args ) throws IOException {
File f = new File ( " a.txt " ) ; FileOutputStream fop = new FileOutputStream ( f ) ;
// Build FileOutputStream Object, file does not exist will be automatically created OutputStreamWriter writer = new OutputStreamWriter ( fop , " UTF-8 " ) ;
// Build OutputStreamWriter object, parameters can specify the encoding, the default is the operating system default encoding, windows is gbk Writer . append ( " Chinese input " ) ; // write to buffer Writer . append ( " \r \n " ) ; // Line feed Writer . append ( " English " ) ; // Refresh cache flush, write to file, if there is no content written below, direct close will also write Writer . close ( ) ; // Closes the write stream and writes the contents of the buffer to the file, so the comment above is fop . close ( ) ; // Close output stream and release system resources FileInputStream fip = new FileInputStream ( f ) ; // Build a FileInputStream object InputStreamReader reader = new InputStreamReader ( fip , " UTF-8 " ) ; // Build InputStreamReader object, same as encoding and writing StringBuffer sb = new StringBuffer ( ) ; while ( reader . ready ( ) ) {
sb . append ( ( char ) reader . read ( ) ) ; // convert to char added to StringBuffer object }
System . out . println ( sb . toString ( ) ) ; reader . close ( ) ; // Close the read stream fip . close ( ) ; // Close the input stream and release system resources }
}
File and I/O
There are also some classes on files and I/O. We also need to know:
- File Class (class)
- FileReader Class (class)
- FileWriter Class (class)
Java directory
Create a directory:
There are two ways in the File class to create a folder:
- The mkdir( ) method creates a folder and returns true if successful, false if it fails. A failure indicates that the path specified by the File object already exists, or 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:
CreateDir.java file code:
import java.io.File;
public class CreateDir { public static void main(String args[]) { String dirname = "/tmp/user/java/bin"; File d = new File(dirname); //Create directory now d.mkdirs(); } }
public class CreateDir { public static void main(String args[]) { String dirname = "/tmp/user/java/bin"; File d = 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 on UNIX and Windows. If you use the delimiter (/) in the Windows version of Java, the path is still 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, calling the isDirectory() method returns true.
You can extract the list of files and folders it contains by calling the list() method on that object.
The following example shows how to use the list() method to check what is contained in a folder:
DirList.java file code:
import java.io.File;
public class DirList {
public static void main(String args[]) {
String dirname = "/tmp";
File f1 = new File(dirname);
File f = new File ( 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 + " not a directory " ) ; }
}
}
if (f1.isDirectory())
{ System . out . println( " directory " + dirname ) ;
String s [ ] = f1 . list ( ) ;
for ( int i = 0 ; i < s . length ; i ++ ) {File f = new File ( 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 + " not a directory " ) ; }
}
}
The above example compiled and run results are as follows:
Directory / tmp Bin is a directory lib is a directory demo is a directory test . txt is a file README is a file index . html is a file include is a directory
Delete a directory or file
Deleting a file can use the java.io.File.delete() method.
The following code will delete the directory /tmp/java/ even if the directory is not empty.
Test the directory structure:
/tmp/ java / |-- 1.log |-- test
DeleteFileDemo.java file code:
import java.io.File;
public class DeleteFileDemo {
public static void main(String args[]) {
// Modify it to your own test directory
File folder = new File("/tmp/java/");
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();
}
}
Comments
Post a Comment