java OutputStreamWriter类 作者:马育民 • 2022-04-12 22:02 • 阅读:10096 # 说明 [](/upload/0/0/1IX3b1LyeOMa.png) `OutputStreamWriter` 是 从字符流到字节流的桥梁:将 **字符** 按照指定的 `charset` 转成 **字节**,然后写入到流中。 如果不指定字符集,用平台的默认字符集。操作系统默认字符集: - windows10、linux、macos,默认字符集是 `UTF-8` - windows8以前,默认字符集是 `GBK` # 构造方法 创建一个使用默认字符编码的OutputStreamWriter: ``` OutputStreamWriter(OutputStream out) ``` 创建一个使用给定字符集的OutputStreamWriter: ``` OutputStreamWriter(OutputStream out, Charset cs) ``` 创建一个使用命名字符集的OutputStreamWriter: ``` OutputStreamWriter(OutputStream out, String charsetName) ``` # 使用 通常 搭配 `BufferedWriter` 使用,该类支持 `newLine()` 方法,输出一个换行符,该换行符与平台有关 - Windows系统里,换行是 `\r\n`; - Unix、linux、Mac OS系统里,换行是 `\n`; # 例子 ``` public static void write(String path,String charset,String content) throws IOException{ BufferedWriter bw = null; OutputStreamWriter osw = null; FileOutputStream fos = null; try{ fos = new FileOutputStream(path); osw = new OutputStreamWriter(fos,charset); bw = new BufferedWriter(osw); bw.write(content); }finally{ if(bw!=null){ bw.close(); } if(osw != null){ osw.close(); } if(fos != null){ fos.close(); } } } ``` 测试: ``` public static void main(String[] args) { try { S1读写文本文件封装类.write("d:\\2.txt", "UTF-8", "好好学习!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ``` 原文出处:http://malaoshi.top/show_1IX37VI9D1Dw.html