Previously, we described how to use the File class to operate the attributes of files or directories, but the File class cannot access the File content, that is, it cannot read or write data from or to the File. Therefore, the following will introduce how to read and write files through "stream" in java.
Concept of flow
Stream is an abstract concept. It refers to a series of data (characters or bytes). It is a channel that sends information in a first in first out manner.
When the program needs to read data, it will open a stream to the data source, which can be a file, memory, or network connection. Similarly, when the program needs to write data, it will open a stream to the destination. At this time, you can imagine that the data seems to "flow" in it.
Generally speaking, the characteristics of flow are as follows:
FIFO: the data first written to the output stream is first read by the input stream.
Sequential access: you can write a string of bytes to the stream one by one. When reading, you will also read a string of bytes in writing order. You cannot access the middle data randomly. (except RandomAccessFile)
Read only or write only: each stream can only be one kind of input stream or output stream. It cannot have two functions at the same time. Input stream can only read and output stream can only write. In a data transmission channel, if you want to write data and read data, you need to provide two streams respectively.
Classification of IO streams
- According to the direction of data flow: input flow and output flow
- By processing data unit: byte stream, character stream
- By function: node flow, processing flow
Common methods of InputStream class
int read(): reads the data of the next byte from the input stream and returns the integer representation of the byte. If it reads to the end of the input stream, it returns - 1. Cannot output Chinese
public class TestIO { public static void main(String[] args) throws IOException { //FileInputStream fis=new FileInputStream("a1.txt"); File f=new File("a1.txt"); FileInputStream fis=new FileInputStream(f); // For (int i = 0; I < f.length(); I + +) {/ / set a loop to realize full-text output // int read = fis.read(); / / the data type is int, which needs to be forcibly converted to char // System.out.print((char) read); / / result: t -- the first value in a1 file // } int temp; while((temp=fis.read())!=-1){//The read() method runs only once, reading one at a time to ensure full output System.out.println((char)temp); } } }
The results are as follows:
Extension: use StringBUilder dynamic string array to output text
public class TestIO { public static String readFile(String path) throws IOException { FileInputStream fis=new FileInputStream(path); StringBuilder sb=new StringBuilder();//The dynamic string is an array to receive each byte int temp; while((temp=fis.read())!=-1){ sb.append((char)temp);//Add to dynamic string array } return sb.toString(); } public static void main(String[] args) throws IOException { File f=new File("a1.txt"); FileInputStream fis=new FileInputStream(f); String s = readFile("a1.txt");//Call the readFile method System.out.println(s); } }
int read(byte[] b): reads data from the input stream, stores the data in the buffer array B, and returns the number of bytes actually read. If read to the end of the input stream, it returns - 1. Chinese arrays can be output.
public static String readFileBytes(String path) throws IOException{ FileInputStream fis=new FileInputStream(path); byte[] b=new byte[fis.available()];//fis.available() the number of bytes that can be read from the input stream fis.read(b); return new String(b); } public static void main(String[] args) throws IOException { File f=new File("a1.txt"); FileInputStream fis=new FileInputStream(f); String s = readFileBytes("a1.txt");//Call the readFileBytes method System.out.println(s); }
Do not throw an exception, and use try catch to solve the exception
public static String readFileBytes(String path){ FileInputStream fis=null; byte[] b=null; try { fis = new FileInputStream(path); b = new byte[fis.available()];//fis.available() the number of bytes that can be read from the input stream fis.read(b); }catch(IOException e){ e.printStackTrace(); } finally{ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } return new String(b); }
int read(byte[] b, int off,int len): read the bytes with the maximum length of len from the input stream and save them to array b, starting from off.
public static String readFileBytes(String path) throws IOException{ FileInputStream fis=new FileInputStream(path); byte[] b=new byte[fis.available()];//fis.available() the number of bytes that can be read from the input stream fis.read(b,5,10); return new String(b); } public static void main(String[] args) throws IOException { File f=new File("a1.txt"); FileInputStream fis=new FileInputStream(f); String s = readFileBytes("a1.txt");//Call the readFileBytes method System.out.println(s); }
Common methods of OutputStream:
void write(int c): write the specified byte data to this output stream. There can be no Chinese in the source file!!!
public static void writeFile(String path,String s)throws IOException{ FileOutputStream fos=new FileOutputStream(path); for (int i = 0; i < s.length() ; i++) { char c = s.charAt(i); fos.write(c); } fos.close(); } public static void main(String[] args) throws IOException { File f=new File("a1.txt"); FileInputStream fis=new FileInputStream(f); String s = readFileBytes("a1.txt");//Call the readFileBytes method System.out.println(s); writeFile("b.txt",s);
void write(byte[] buf): writes all bytes in the array buf to this output stream.
public static void writeFileBytes(String path,String s)throws IOException{ FileOutputStream fos=new FileOutputStream(path); byte[] b=s.getBytes(); fos.write(b); fos.close(); } public static void main(String[] args) throws IOException { File f=new File("a1.txt"); FileInputStream fis=new FileInputStream(f); String s = readFileBytes("a1.txt");//Call the readFileBytes method System.out.println(s); writeFileBytes("b1.txt",s);
Add a true after it to realize that the original file is not overwritten. 2. Append on its basis!
void write(byte[] b, int off,int len): outputs byte data of length len of byte array from offset off to output stream