純文本-FileOutputStream的解碼方式


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();
            }
        }
    }
}

 文件類型:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM