1. 程式人生 > >java 字元轉換流

java 字元轉換流

 

package cn.sasa.demo4;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        
/** * FileWriter 不能指定字元編碼 * * 用OutputStreamWriter * 將字元流轉成位元組流 * */ // writeGBK(); //writeUTF8(); //readGBK(); readUTF8(); } static void writeGBK() throws IOException { //1、建立一個FileOutputStream,繫結目的 FileOutputStream output = new
FileOutputStream("d:/sasa/test1225.txt"); //2、建立一個OutputStreamWriter,指定字元編碼, //建構函式的第二個字串引數指定字元編碼,不寫預設是系統的預設編碼GBK OutputStreamWriter writer = new OutputStreamWriter(output); //3、呼叫write writer.write("你好"); writer.flush(); writer.close(); }
static void writeUTF8() throws IOException { FileOutputStream output = new FileOutputStream("d:\\sasa\\utf.txt"); OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8"); writer.write("啦啦啦"); writer.flush(); writer.write("你好"); writer.flush(); writer.close(); } static void readGBK() throws IOException { FileInputStream input = new FileInputStream("d:\\sasa\\test1225.txt"); InputStreamReader reader = new InputStreamReader(input); char[] charArr = new char[1024]; @SuppressWarnings("unused") int len = 0; while((len = reader.read(charArr)) != -1) { System.out.print(new String(charArr)); } reader.close(); } static void readUTF8() throws IOException { FileInputStream input = new FileInputStream("d:\\sasa\\utf.txt"); InputStreamReader reader = new InputStreamReader(input , "UTF-8"); char[] charArr = new char[1024]; @SuppressWarnings("unused") int len = 0; while((len = reader.read(charArr)) != -1) { System.out.print(new String(charArr)); } reader.close(); } }