1. 程式人生 > >輸入輸出流讀取本機txt文件:不能將中文字元流轉化為char 因為char一個位元組,中文在UTF-8的情況下是三個位元組,會出現字元流擷取

輸入輸出流讀取本機txt文件:不能將中文字元流轉化為char 因為char一個位元組,中文在UTF-8的情況下是三個位元組,會出現字元流擷取

package interview;

import org.junit.Test;

import java.io.*;

public class TestInOrOutStream {

class  m {
    @Test
    void x(){
        System.out.println("kkk");
    }

}
public static void main(String[] args) {
    String i;
    BufferedReader is = null;
    try {
       String file = "G://《國富論》全本.txt";
       is = new BufferedReader(new FileReader(file));

      //  InputStream is = new MyOwnInputStream(new BufferedInputStream(new FileInputStream("G://《國富論》全本.txt")), "UTF-8");
     //   InputStream is = new MyOwnInputStream(new BufferedInputStream(new FileInputStream("G://國富論(英文版).txt")), "UTF-8");
        while (( i = is.readLine()) != null) {
            //不能將中文字元流轉化為char 因為char一個位元組,中文在UTF-8的情況下是三個位元組,會出現字元流擷取
            System.out.print(i);


        }
        System.out.println("中文亂碼沒有解決");
        is.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

}


static class MyOwnInputStream extends FilterInputStream {
    public MyOwnInputStream(InputStream in, String s) {
        super(in);
    }

    public int read() throws IOException {
        int c = 0;
        if ((c = super.read()) != -1) {
            if (Character.isLowerCase((char) c))
                return Character.toUpperCase((char) c);

            else if (Character.isUpperCase((char) c))
                return Character.toLowerCase((char) c);

            else {
                return c;
            }

        } else {
            return -1;
        }
    }
}}

在這裡插入圖片描述