Java Stream, File, and IO
Streams, Files, and IO (Input/Output) in Java are the infrastructure for handling data reading and writing; they allow programs to interact with external data (such as files, networks, system input, etc.).
The java.io package is a core package in the Java standard library, providing classes for system input and output. It contains tools for handling data streams (byte streams and character streams), file reading and writing, serialization, and data formatting.
java.io is the foundational package for file operations, stream operations, and low-level IO operations.
The streams in the java.io package support many formats, such as: primitive types, objects, localized character sets, and so on.
A stream can be understood as a sequence of data. An input stream represents reading data from a source; an output stream represents writing data to a target.
Reading console input
Java's console input is done by System.in.
To obtain a character stream bound to the console, you can wrap System.in in a BufferedReader object to create a character stream.
The following is the basic syntax for creating a BufferedReader:
BufferedReader
br
=
new
BufferedReader
(
new
InputStreamReader
(
System
.
in
)
)
;
After a 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.
Reading multi-character input from the console
To read a character from a BufferedReader object, use the read() method; its syntax is as follows:
int
read
(
)
throws
IOException
Each time the read() method is called, it reads one character from the input stream and returns that character as an integer value. It returns -1 when the stream ends. This method throws IOException.
The following program demonstrates using the read() method to continuously read characters from the console until the user inputs q.
BRRead.java file code:
//
Use BufferedReader to read characters from 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
(
"
Input characters, press 'q' to exit.
"
)
;
//
Read character
do
{
c
=
(
char
)
br
.
read
(
)
;
System
.
out
.
println
(
c
)
;
}
while
(
c
!=
'
q
'
)
;
}
}
The compilation and execution results of the above example are as follows:
输入字符, 按下 'q' 键退出。
runoob
r
u
n
o
o
b
q
q
Reading a string from the console
Reading a string from standard input requires the readLine() method of BufferedReader.
Its general format is:
String
readLine
(
)
throws
IOException
The following program reads and displays lines of characters until you enter the word "end".
BRReadLines.java file code:
//
Use BufferedReader to read characters from 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 compilation and execution results of the above example 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
For versions after JDK 5, we can also use the Java Scanner class to obtain console input.
Console output
As introduced earlier, console output is done by print() and println(). These methods are all defined by the PrintStream class, and System.out is a reference to an object of this class.
PrintStream inherits from the OutputStream class and implements the write() method. Thus, write() can also be used to write to the console.
The simplest form of write() defined by PrintStream is as follows:
void
write
(
int
byteval
)
This method writes the low eight bits of byteval to the stream.
Example
The following example uses write() to output the character "A" and the following newline 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
'
)
;
}
}
Running the above example outputs the "A" character in the output window
A
**Note:** The write() method is not used often, because print() and println() are more convenient to use.
Reading and writing files
As mentioned earlier, a stream is defined as a sequence of data. An input stream is used to read data from a source, and an output stream is used to write data to a target.
The figure below is a class hierarchy diagram describing input and output streams.
Byte streams (handling binary data)
Byte streams are used to process binary data, such as files, images, videos, etc.
| Class Names | Type | Description |
|---|---|---|
InputStream |
Abstract class (input stream) | The superclass of all byte input streams, handling byte input operations. |
OutputStream |
Abstract class (output stream) | The superclass of all byte output streams, handling byte output operations. |
FileInputStream |
Input stream | Reads byte data from a file. |
FileOutputStream |
Output stream | Writes byte data to a file. |
BufferedInputStream |
Input stream | Provides buffering for byte input streams, improving read efficiency. |
BufferedOutputStream |
Output stream | Provides buffering for byte output streams, improving write efficiency. |
ByteArrayInputStream |
Input stream | Uses a byte array in memory as the input source. |
ByteArrayOutputStream |
Output stream | Writes data to a byte array in memory. |
DataInputStream |
Input stream | Allows reading Java primitive data types (such as int, float, boolean). |
DataOutputStream |
Output stream | Allows writing Java primitive data types to the output stream. |
ObjectInputStream |
Input stream | Reads serialized objects from the input stream. |
ObjectOutputStream |
Output stream | Serializes objects and writes them to the output stream. |
PipedInputStream |
Input stream | Used to read byte data in a pipe, usually used together with PipedOutputStream . |
PipedOutputStream |
Output stream | Used to write byte data in a pipe, usually used together with PipedInputStream . |
FilterInputStream |
Input stream | A wrapper class for byte input streams, used to filter other input streams. |
FilterOutputStream |
Output stream | A wrapper class for byte output streams, used to filter other output streams. |
SequenceInputStream |
Input stream | Concatenates multiple input streams into a single input stream for processing. |
Character streams (handling text data)
Character streams are used to process text data, such as reading and writing strings or files.
| Class Names | Type | Description |
|---|---|---|
Reader |
Abstract class (input stream) | The superclass of all character input streams, handling character input operations. |
Writer |
Abstract class (output stream) | The superclass of all character output streams, handling character output operations. |
FileReader |
Input stream | Reads character data from a file. |
FileWriter |
Output stream | Writes character data to a file. |
BufferedReader |
Input stream | Provides buffering for character input streams, supports line-by-line reading, improving read efficiency. |
BufferedWriter |
Output stream | Provides buffering for character output streams, supports line-by-line writing, improving write efficiency. |
CharArrayReader |
Input stream | Uses a character array as the input source. |
CharArrayWriter |
Output stream | Writes data to a character array. |
StringReader |
Input stream | Uses a string as the input source. |
StringWriter |
Output stream | Writes data to a string buffer. |
PrintWriter |
Output stream | A convenient character output stream that supports automatic flushing and formatted output. |
PipedReader |
Input stream | Used to read character data in a pipe, usually used together with PipedWriter . |
PipedWriter |
Output stream | Used to write character data in a pipe, usually used together with PipedReader . |
LineNumberReader |
Input stream | A buffered character input stream with line numbers, allowing tracking of the line number read. |
PushbackReader |
Input stream | Allows pushing characters back into the stream after reading, so they can be read again. |
Helper classes (other important classes)
Helper classes provide support for files, directories, and random file access.
| Class Names | Type | Description |
|---|---|---|
File |
File and directory operations | Used to represent a file or directory and provide file operations such as creation, deletion, renaming, etc. |
RandomAccessFile |
Random access file | Supports random access to files, allowing reading and writing data from any position in the file. |
Console |
Console input and output | Provides input and output support for the system console. |
The two important streams to be discussed next are FileInputStream and FileOutputStream.
FileInputStream
This stream is used to read data from a file; its object can be created using the keyword new.
There are several constructors available to create an object.
You can use a string-type file name 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 must first use the File() method to create a file object:
File
f
=
new
File
(
"
C:/java/hello
"
)
;
InputStream
in
=
new
FileInputStream
(
f
)
;
After creating an InputStream object, you can use the following methods to read the stream or perform other stream operations.
| Method | Description | Example Code |
|---|---|---|
int read() |
Reads one byte of data, returning an integer between 0 and 255. Returns -1 if the end of the stream is reached. | int data = inputStream.read(); |
int read(byte[] b) |
Reads bytes from the input stream and stores them in the byte array b , returning the actual number of bytes read. Returns -1 if the end of the stream is reached. |
byte[] buffer = new byte[1024]; int bytesRead = inputStream.read(buffer); |
int read(byte[] b, int off, int len) |
Reads at most len bytes and stores them in the byte array b 's off at the offset position, returning the actual number of bytes read. Returns -1 if the end of the stream is reached. |
byte[] buffer = new byte[1024]; int bytesRead = inputStream.read(buffer, 0, buffer.length); |
long skip(long n) |
Skips and discards n bytes from the input stream, returning the actual number of bytes skipped. |
long skippedBytes = inputStream.skip(100); |
int available() |
Returns the number of bytes that can be read (without blocking). | int availableBytes = inputStream.available(); |
void close() |
Closes the input stream and releases all resources associated with the stream. | inputStream.close(); |
void mark(int readlimit) |
Sets a mark at the current position in the stream,readlimit is the upper limit of bytes that can be read. |
inputStream.mark(1024); |
void reset() |
Repositions the stream to the last marked position; if there is no mark or the mark is invalid, throws IOException. |
inputStream.reset(); |
boolean markSupported() |
Checks whether the current input stream supports mark() and reset() operation. |
boolean isMarkSupported = inputStream.markSupported(); |
Besides InputStream, there are some other input streams; refer to the links below for more details:
FileOutputStream
This class is used to create a file and write data to the file.
If the target file does not exist when this stream opens the file for output, the stream will create the file.
There are two constructors that can be used to create a FileOutputStream object.
Use a string-type file name to create an output stream object:
OutputStream
f
=
new
FileOutputStream
(
"
C:/java/hello
"
)
You can also use a file object to create an output stream to write the file. We must first use the File() method to create a file object:
File
f
=
new
File
(
"
C:/java/hello
"
)
;
OutputStream
fOut
=
new
FileOutputStream
(
f
)
;
After creating an OutputStream object, you can use the following methods to write to the stream or perform other stream operations.
| Method | Description | Example Code |
|---|---|---|
void write(int b) |
Writes the specified byte to the output stream,b the low 8 bits of are written to the stream. |
outputStream.write(255); |
void write(byte[] b) |
Writes the byte array b all bytes in to the output stream. |
byte[] data = "Hello".getBytes(); outputStream.write(data); |
void write(byte[] b, int off, int len) |
Writes the byte array b Starting from offset off starting at len bytes are written to the output stream. |
byte[] data = "Hello".getBytes(); outputStream.write(data, 0, data.length); |
void flush() |
Flushes the output stream and forces out all buffered data, ensuring the data is written to the target output immediately. | outputStream.flush(); |
void close() |
Closes the output stream and releases all resources associated with the stream. No further writing is allowed after closing. | outputStream.close(); |
Besides OutputStream, there are some other output streams; refer to the links below for more details:
Example
The following is an example demonstrating 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
.
(
(
char
)
is
.
read
(
)
"
"
)
;
}
is
.
close
(
)
;
}
catch
(
IOException
e
)
{
System
.
out
.
(
"
Exception
"
)
;
}
}
}
The program above first creates the file test.txt and writes the given numbers into the file in binary form, while also outputting them to the console.
The code above writes in binary, which may cause garbled characters; you can use the following code example to solve the garbled character 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 the FileOutputStream object; if the file does not exist it will be created automatically
OutputStreamWriter
writer
=
new
OutputStreamWriter
(
fop
,
"
UTF-8
"
)
;
//
Build the OutputStreamWriter object; the parameter can specify the encoding, defaulting to the OS default encoding (gbk on Windows)
writer
.
append
(
"
Chinese input
"
)
;
//
Write to the buffer
writer
.
append
(
"
\r
\n
"
)
;
//
Newline
writer
.
append
(
"
English
"
)
;
//
Flush the buffer and write to the file; if there is no more content to write below, closing directly will also write
writer
.
close
(
)
;
//
Close the write stream, which also writes the buffer content to the file, so the above is commented out
fop
.
close
(
)
;
//
Close the output stream and release system resources
FileInputStream
fip
=
new
FileInputStream
(
f
)
;
//
Build the FileInputStream object
InputStreamReader
reader
=
new
InputStreamReader
(
fip
,
"
UTF-8
"
)
;
//
Build the InputStreamReader object, with the same encoding as the write
StringBuffer
sb
=
new
StringBuffer
(
)
;
while
(
reader
.
ready
(
)
)
{
sb
.
append
(
(
char
)
reader
.
read
(
)
)
;
//
Convert to char and add to the StringBuffer object
}
System
.
out
.
println
(
sb
.
toString
(
)
)
;
reader
.
close
(
)
;
//
Close the read stream
fip
.
close
(
)
;
//
Close the input stream and release system resources
}
}
Files and I/O
There are also some classes about files and I/O that we need to know:
Directories in Java
Creating directories:
There are two methods in the File class that can be used to create folders:
- The **mkdir( )** method creates a folder; it returns 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.
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
)
;
//
Now create the directory
d
.
mkdirs
(
)
;
}
}
Compile and execute the code above to create the directory "/tmp/user/java/bin".
Note: Java automatically resolves file path separators according to conventions on both UNIX and Windows. If you use the separator (/) in the Windows version of Java, the path can still be correctly resolved.
Reading a directory
A directory is actually just a File object that contains other files and folders.
If you create a File object and it is a directory, then calling isDirectory() returns true.
You can extract the list of files and folders it contains by calling the list() method on the object.
The example below shows how to use the list() method to check the contents of 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
)
;
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
"
is not a directory
"
)
;
}
}
}
The compilation and execution results of the above example are as follows:
目录 /tmp
bin 是一个目录
lib 是一个目录
demo 是一个目录
test.txt 是一个文件
README 是一个文件
index.html 是一个文件
include 是一个目录
Deleting a directory or file
To delete a file you can use java.io.File.delete() method.
The following code deletes the directory /tmp/java/; note that when deleting a directory, you must ensure there are no other files in that directory for the deletion to succeed, otherwise the deletion will fail.
Test directory structure:
/tmp/java/
|-- 1.log
|-- test
DeleteFileDemo.java file code:
import
java
.
io
.
File
;
public
class
DeleteFileDemo
{
public
static
void
main
(
String
[
]
args
)
{
//
Replace this with your own test directory
File
folder
=
new
File
(
"
/tmp/java/
"
)
;
deleteFolder
(
folder
)
;
}
//
Deleting 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
(
)
;
}
}
