The Java.io package contains almost all the classes needed to operate input and output. All these stream classes represent input sources and output destinations.
Streams in the Java.io package support many formats, such as basic types, objects, localized character sets, etc.
A stream can be understood as a sequence of data. An input stream represents reading data from a source, and an 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.
But this section covers the most basic functions related to streams and I/O. We will learn these functions through examples one by one.
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:
BufferedReaderbr=newBufferedReader(new InputStreamReader(System.in));
After 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.
To read a character from a BufferedReader object, use the read() method, whose syntax is as follows:
intread()throwsIOException
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 IOException.
The following program demonstrates using the read() method to continuously read characters from the console until the user enters "q".
//使用BufferedReader在控制台读取字符importjava.io.*; publicclassBRRead{ publicstaticvoidmain(Stringargs[])throwsIOException { charc; //使用System.in创建BufferedReader BufferedReaderbr=newBufferedReader(new InputStreamReader(System.in)); System.out.println("输入字符, 按下'q' 键退出."); //读取字符do{ c=(char)br.read(); System.out.println(c); }while(c!='q'); } }
The compilation and running results of the above example are as follows:
输入字符, 按下'q' 键退出. 123abcq 1 2 3 a b c q
Reading a string from standard input requires using the readLine() method of BufferedReader.
Its general format is:
StringreadLine()throwsIOException
The following program reads and displays lines of characters until you enter the word "end".
//使用BufferedReader在控制台读取字符importjava.io.*; publicclassBRReadLines{ publicstaticvoidmain(Stringargs[])throwsIOException { //使用System.in创建BufferedReader BufferedReaderbr=newBufferedReader(new InputStreamReader(System.in)); Stringstr; System.out.println("Enterlinesoftext."); System.out.println("Enter'end'toquit."); do{ str=br.readLine(); System.out.println(str); }while(!str.equals("end")); } }
The compilation and running results of the above example are as follows:
Enterlinesoftext. Enter'end'toquit. Thisislineone Thisislineone Thisislinetwo Thisislinetwo end end
As mentioned before, console output is completed by print() and println(). These methods are defined by the PrintStream class, and System.out is a reference to the object of this class.
PrintStream inherits the OutputStream class and implements the method write(). In this way, write() can also be used to write operations to the console.
PrintStream defines write() in its simplest form as follows:
voidwrite(intbyteval)
This method writes the lower octets of byteval to the stream.
The following example uses write() to print the character "A" followed by a newline character to the screen:
importjava.io.*; //演示System.out.write(). publicclassWriteDemo{ publicstaticvoidmain(Stringargs[]){ intb; 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 often used because the print() and println() methods are more convenient to use.
As mentioned before, 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 target.
The following figure is a class hierarchy diagram describing the input stream and output stream.
The two important streams that will be discussed below are FileInputStream and FileOutputStream:
This stream is used to read data from a file, and its objects can be created using the keyword new.
There are various constructor methods used to create objects.
You can use a string file name to create an input stream object to read the file:
InputStreamf=newFileInputStream("C:/java/hello");
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:
Filef=newFile("C:/java/hello"); InputStreamf=newFileInputStream(f);
After creating an InputStream object, you can use the following methods to read the stream or perform other stream operations.
serial number | Methods and Description |
---|---|
1 | public void close() throws IOException{} Closes this file input stream and releases all system resources related to this stream. Throws an IOException. |
2 | protected void finalize()throws IOException {} This method clears the connection to the file. Make sure to call the close method of the file input stream when it is no longer referenced. Throws an IOException. |
3 | public int read(int r)throws IOException{} This method reads specified bytes of data from the InputStream object. Returned as an integer value. Returns the next byte of data, or -1 if the end has been reached. |
4 | public int read(byte[] r) throws IOException{} This method reads r.length bytes from the input stream. Returns the number of bytes read. If it is the end of the file, -1 is returned. |
5 | public int available() throws IOException{} Returns the number of bytes that can be read from this input stream without blocking by the next method call on this input stream. Returns an integer value. |
In addition to InputStream, there are some other input streams. For more details, please refer to the link below:
ByteArrayInputStream
DataInputStream
This class is used to create a file and write data to the 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 that can be used to create FileOutputStream objects.
Create an output stream object using a string filename:
OutputStreamf=newFileOutputStream("C:/java/hello")
You can also use a file object to create an output stream to write to the file. We first have to create a file object using the File() method:
Filef=newFile("C:/java/hello"); OutputStreamf=newFileOutputStream(f);
After creating the OutputStream object, you can use the following methods to write to the stream or perform other stream operations.
serial number | Methods and Description |
---|---|
1 | public void close() throws IOException{} Closes this file input stream and releases all system resources related to this stream. Throws an IOException. |
2 | protected void finalize()throws IOException {} This method clears the connection to the file. Make sure to call the close method of the file input stream when it is no longer referenced. Throws an IOException. |
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 the bytes of length w.length in the specified array to OutputStream. |
In addition to OutputStream, there are some other output streams. For more details, please refer to the link below:
ByteArrayOutputStream
DataOutputStream
Here is an example demonstrating the usage of InputStream and OutputStream:
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, writes the given number into the file in binary form, and outputs it to the console.
Since the above code is written in binary, there may be garbled characters. You can use the following code examples to solve the garbled code problem:
//文件名:fileStreamTest2.java importjava.io.*; publicclassfileStreamTest2{ publicstaticvoidmain(String[]args)throwsIOException{ Filef=newFile("a.txt"); FileOutputStreamfop=newFileOutputStream(f); //构建FileOutputStream对象,文件不存在会自动新建OutputStreamWriterwriter=newOutputStreamWriter(fop,"UTF-8"); //构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk writer.append("中文输入"); //写入到缓冲区writer.append("rn"); //换行writer.append("English"); //刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入writer.close(); //关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉fop.close(); //关闭输出流,释放系统资源 FileInputStreamfip=newFileInputStream(f); //构建FileInputStream对象InputStreamReaderreader=newInputStreamReader(fip,"UTF-8"); //构建InputStreamReader对象,编码与写入相同 StringBuffersb=newStringBuffer(); while(reader.ready()){ sb.append((char)reader.read()); //转成char加到StringBuffer对象中 } System.out.println(sb.toString()); reader.close(); //关闭读取流fip.close(); //关闭输入流,释放系统资源 } }
There are also some classes about files and I/O that we also need to know:
File Class(class)
FileReader Class(class)
FileWriter Class(class)
There are two methods in the File class that can be used to create folders:
The mkdir() method creates a folder and returns true if successful and false if failed. 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:
importjava.io.File; publicclassCreateDir{ publicstaticvoidmain(Stringargs[]){ Stringdirname="/tmp/user/java/bin"; Filed=newFile(dirname); //现在创建目录d.mkdirs(); } }
Compile and execute the above code to create the directory "/tmp/user/java/bin".
Note: Java automatically resolves file path separators by convention on UNIX and Windows. If you use the delimiter (/) in the Windows version of Java, the path will still be parsed correctly.
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 will return true.
You can extract the list of files and folders it contains by calling the list() method on the object.
The example shown below illustrates how to use the list() method to check the contents of a folder:
importjava.io.File; publicclassDirList{ publicstaticvoidmain(Stringargs[]){ Stringdirname="/tmp"; Filef1=newFile(dirname); if(f1.isDirectory()){ System.out.println("Directoryof"+dirname); Strings[]=f1.list(); for(inti=0;i<s.length;i++){ Filef=newFile(dirname+"/"+s[i]); if(f.isDirectory()){ System.out.println(s[i]+"是一个目录"); }else{ System.out.println(s[i]+"是一个文件"); } } }else{ System.out.println(dirname+"不是一个目录");
} } }
The compilation and running results of the above example are as follows:
目录/tmp bin 是一个目录lib 是一个目录demo 是一个目录test.txt 是一个文件README 是一个文件index.html 是一个文件include 是一个目录
To delete a file, use the java.io.File.delete() method.
The following code will delete the directory /tmp/java/. It should be noted that when deleting a certain directory, you must ensure that there are no other files in the directory to delete it correctly, otherwise the deletion will fail.
Test directory structure:
/tmp/java/ |-- 1.log |-- test
import java.io.File; public class DeleteFileDemo { public static void main(String args[]) { // 这里修改为自己的测试目录File folder = new File("/tmp/java/"); deleteFolder(folder); } // 删除文件及目录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(); } }