1.通過string.getBytes(charsetNane)獲得的字節數組,字節數組的編碼方式,決定了FileOutStream寫出文件的格式
例1:字節數組采用“GBK”編碼,write生成的文件也將是“GBK”編碼
package cn.edu.uestc.IO; import java.io.*; public class TestFileOutputStream01 { public static void main(String[] args){ //源 File src = new File("abc5.txt");//如果沒有文件,自動創建 //流 OutputStream os = null; try { os = new FileOutputStream(src,false); //操作 String str = "你好,哈哈哈"; byte[] bytes = str.getBytes("GBK");//字節數組采用GBK編碼 os.write(bytes,0,bytes.length); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //釋放資源 try{ if (os!=null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
文件類型:
例2:字節數組采用“UTF-8”編碼,write生成的文件也將是“UTF-8”編碼
package cn.edu.uestc.IO; import java.io.*; public class TestFileOutputStream02 { public static void main(String[] args){ //創建源 File src = new File("abc6.txt"); //生成流 OutputStream os = null; try { os = new FileOutputStream(src); //操作 String str = "你好,哈哈哈"; byte[] bytes = str.getBytes("UTF-8");//字節數組采用"UTF-8"編碼 os.write(bytes,0,bytes.length); os.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if (null!=os){ os.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
文件類型: