**1.解决从文本文件中读入数据后输出,发现中文乱码问题。**下面的这个两个例子很好的解决了这个问题!
package day1029; import java.io.*; public class TestPrintStreamAndWriter { public static void main(String[] args) { new TestPrintStreamAndWriter().TestPrintWriter(); } private void TestPrintStream() { // 从读出的字节中直接转换为gbk 所以不会乱码 BufferedInputStream bis = null; PrintStream ps = null; try { bis = new BufferedInputStream(new FileInputStream(new File("D:\\文档\\p.txt"))); // 把输出流设置为控制台 ps = new PrintStream(System.out); byte[] bytes = new byte[bis.available()]; if (bis.read(bytes, 0, bytes.length) > 0) { ps.print(new String(bytes, "gbk")); } } catch (IOException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void TestPrintWriter() { BufferedReader br = null; PrintWriter pw = null; try { // 文件的读取顺序是FileInputStream以字节的方式把文件读出来, // 然后通过转换流InputStreamReader把它以gbk的方式编码, // 编成gbk的字符,然后BufferedReader再读取转换后的字符, // 这样输出就不会乱码了 br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\文档\\p.txt"), "gbk")); // 重定向 pw = new PrintWriter(System.out); String s = null; while ((s = br.readLine()) != null) { pw.println(s); } } catch (IOException e) { e.printStackTrace(); } finally { if (pw != null) { pw.close(); } if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }TestPrintStream()方法是以字节流的方式读取数据,然后在输出的时候new String(bytes, "gbk")是这样的。意思就是,Stirng要把bytes里的字节以gbk的方式进行编码,然后再输出。