举例说明使用BufferedReader时出现乱码时的解决方法

解决方法如下:

BufferedReader br=new BufferedReader(new InputStreamReader(connectiton.getInputStream(),"GB2312"));
或者
BufferedReader br=new BufferedReader(new InputStreamReader(connectiton.getInputStream(),"GBK"));

具体举例:

     FileInputStream fileInputStream = new FileInputStream("文件路径");
     InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"GB2312");//或者"GBK"
     BufferedReader br= new BufferedReader(inputStreamReader);

 

现以第二届ITAT大赛最后一道编程题为例

 

1.编写一个Java程序要求:开启一个文本文件,一次读取其内的一行文本。令每一行形成一个String,并将读出的String对象置于LinkedList中。请以相反次序印出LinkedList内的所有文本行。

 

package MyTest;

import java.io.*;
import java.util.LinkedList;
import java.util.ListIterator;

/**
 *
 * @author Administrator
 */
public class Test22 {

    public static void main(String args[]) throws FileNotFoundException, IOException {
        //FileReader fr = new FileReader("D:/我的文档/NetBeansProjects/IT/src/MyTest/c.txt");
        FileInputStream fr=new FileInputStream("D:/我的文档/NetBeansProjects/IT/src/MyTest/b.txt");
        InputStreamReader is=new InputStreamReader(fr,"GB2312");
        BufferedReader br = new BufferedReader(is);
        LinkedList ll = new LinkedList();
        String s;
        while ((s = br.readLine()) != null) {           
            ll.addFirst(s);
        }
        br.close();
        ListIterator li = ll.listIterator(ll.size());
        while (li.hasPrevious()) {
            System.out.println(li.previous());
        }
    }
}

你可能感兴趣的:(java,编程,String,Class,文档,import)