4、IO--字节转换流
整个Java的I/O包中实际上分为字节流和字符流
还存在一组”字节流--字符流“的转换类
1、OutputStreamWriter:是Writer的子类,将输出的字符流变为字节流
即将一个字符流的输出对象变为字节流的输出对象
2、InputStreamReader:是Reader的子类,将输入的字节流转换为字符流
即将一个字节流的输入对象变为字符流的输入对象
关闭规则:
由里到外
字符流转换为字节流OutputStreamWriter
public static void main(String[] args) throws IOException { //1、 File file = new File("d:\\test.txt"); OutputStream out = new FileOutputStream(file); //2、 Writer writer = null; writer = new OutputStreamWriter(out); //3、 writer.write("天长地久"); //4、 writer.close(); out.close(); }
字节流转换为字符流InputStreamReader
public static void main(String[] args) throws IOException { //1、 File file = new File("d:\\test.txt"); InputStream in = new FileInputStream(file); //2、 InputStreamReader reader = null; reader = new InputStreamReader(in); //3、 int res = 0; int len = 0; char [] b = new char[(int) file.length()]; while((res = reader.read()) !=-1){ b[len] = (char) res; len++; } //4、 reader.close(); in.close(); System.out.println(new String(b)); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步