用途:IO工具类(获取getReader and getWriter)
使用场景
IO工具类只是辅助流的读写,并不负责关闭流。原因是流可能被多次读写,读写关闭后容易造成问题。
(获取getReader and getWriter)
(获取getReader and getWriter)
(获取getReader and getWriter)
项目引用
此博文的依据:hutool-5.6.5版本源码
方法明细
方法名称:cn.hutool.core.io.IoUtil.getUtf8Reader(java.io.InputStream)
方法描述
获得一个文件读取器,默认使用UTF-8编码
支持版本及以上
5.1.6
参数描述:
方法明细
方法名称:cn.hutool.core.io.IoUtil.getReader(java.io.InputStream, java.nio.charset.Charset)
方法描述
获得一个Reader
支持版本及以上
参数描述:
StringReader stringReader = null; PushbackReader pushbackReader = null; try { stringReader = new StringReader("123456789"); //PushbackReader允许调用者将一些数据源本身不包含的字符插入到流的任意位置 pushbackReader = IoUtil.getPushBackReader(stringReader,100); StringBuilder stringBuilder = new StringBuilder(); char[] buff = new char[3]; //第一步,首先读取 “123” int n = pushbackReader.read(buff, 0, 3); stringBuilder.append(buff); System.out.println("第一步,读取了 " + n + " 个字符:"); System.out.println(buff); //第二步,unread:abc, de, fghi pushbackReader.unread(new char[]{'a', 'b', 'c'}); pushbackReader.unread(new char[]{'d', 'e'}); pushbackReader.unread(new char[]{'f', 'g', 'h', 'i'}); int c = 0; while ((c = pushbackReader.read()) != -1){ stringBuilder.append((char) c); } System.out.println("最终读取的数据:" + stringBuilder.toString()); }catch (IOException e){ //抛出一个运行时异常(直接停止掉程序) throw new RuntimeException("运行时异常",e); } finally { try { //如果是空的 说明流创建失败 失败了不需要关闭 if (stringReader != null) { stringReader.close(); } } catch (Exception e) { //关闭资源失败 停止程序 throw new RuntimeException("关闭资源失败"); }finally { try { if (pushbackReader != null) { pushbackReader.close(); } } catch (Exception e) { throw new RuntimeException("关闭资源失败"); } } }
File dest = new File("C:\\Users\\Administrator\\Desktop\\xuzhu/getWriterTest1.txt") ; FileOutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; try { //创建流 outputStream = new FileOutputStream(dest); //新new OutputStreamWriter对象,记得关闭回收 outputStreamWriter = IoUtil.getWriter(outputStream,CharsetUtil.CHARSET_UTF_8); String content = "1hello 小虚竹\n2hello 小虚竹"; int c; for (int i = 0; i < content.length(); i++) { c = content.charAt(i); outputStreamWriter.write((char) c); } outputStreamWriter.flush(); } catch (IOException e) { //抛出一个运行时异常(直接停止掉程序) throw new RuntimeException("运行时异常",e); } finally { try { //如果是空的 说明流创建失败 失败了不需要关闭 if (outputStream != null) { outputStream.close(); } } catch (Exception e) { //关闭资源失败 停止程序 throw new RuntimeException("关闭资源失败"); }finally { try { if (outputStreamWriter != null) { outputStreamWriter.close(); } } catch (Exception e) { throw new RuntimeException("关闭资源失败"); } } }