Conversion flow
Conversion stream refers to the functional conversion that can realize byte stream and character stream operations. For example, when outputting, OutputStream needs to change the content into a byte array and then output it, and Writer can directly output strings, so many people think that it needs a A conversion mechanism to realize the conversion operation of different stream types. For this reason, there are two classes in the java.io package:
- InouterSteamReader
//定义 public class InputStreamReader extends Reader //构造方法 public InputStreamReader(InputStream in)
- OutputStreamWriter
//定义 public class OutputStreamWriter extends Writer //构造方法 public OutputStreamWriter(OutputStream out)
Incoming byte stream object, use up-cast to convert bit character stream object.
Example: Observe the conversion
public class Writer字符流输出 {
public static void main(String[] args) throws IOException {
File file = new File("F:"+File.separator+"Test"+File.separator+"test.txt");
if(file.getParentFile().exists()){ //没有父路径
file.getParentFile().mkdirs(); //创建一个父路径
}
OutputStream outputStream = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(outputStream); //字节流变为了字符流
writer.write("www.baidu.com"); //直接输出一个字符串,不需要转换为字节数组
writer.close();
}
}
The OutputStream class has a direct subclass of FileOutputStream, and InputStream has a direct subclass of FileInputstream, but let’s observe the inheritance relationship between FileWriter and FileReader:
//FileWrite
public class FileWriter extends OutputStreamWriter
//FileReader
public class FileReader extends InputStreamReader
FileReader inheritance structure
The difference between character stream and byte stream is that the character stream has more buffers, which actually refers to a processing buffer in the middle of the program.