Conversion stream
The conversion of byte stream and character stream can be converted by InputStreamReader and OutputStreamWriter. The following is the inheritance structure and construction method of these two classes
name | Define construction | Construction method |
---|---|---|
InputStreamReader | public class InputStreamReader extends Reader | public InputStreamReader(InputStream in) |
OutputStreamWriter | public class OutputStreamWriter extends Writer | public OutputStreamWriter(OutputStream out) |
Through the above relationship we can find:
- InputStreamReader class constructor receives InputStream class object, and InputStreamReader is a subclass of Reader, which can be directly converted into Reader class object, which means that the received byte input stream can be converted into character input stream;
- The constructor of the OutputStreamWriter class receives an object of the OutputStream class, and OutputStreamWriter is a subclass of Writer, which is directly converted upward to a Writer class object, which means that the received byte output stream can be converted into a character output stream (in the Writer class Provides direct output string operation).
Example: Implement output stream conversion
package Project.Study.WriterClass;
import java.io.*;
public class Test3 {
public static void main(String[]args)throws Exception{
File file=new File("d:"+File.separator+"Test"+File.separator+"test3.txt");//定义要输出文件的路径
if (!file.getParentFile().exists()){//判断父路径是否存在
file.getParentFile().mkdirs();//创建父路径
}
OutputStream outputStream=new FileOutputStream(file);//字节流
Writer writer=new OutputStreamWriter(outputStream);//将OutputStream类对象传递给OutputStreamWriter类的构造方法,而后向上转型为Writer
writer.write("Hello World!!!");//Writer类的方法
writer.flush();
writer.close();
}
}
result: