前提是所读取的文件时UTF-8编码,如果不是,可以文件另存为时修改编码为UTF-8编码,这样的话就不会中文乱码了。
package com.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;public class IoTest {
/**
* @param args */ public static void main(String[] args) { String s=readFile("D:/data.txt"); System.out.println("读取内容为:"+s); } public static String readFile(String fliename){ StringBuffer strbf=new StringBuffer(); String s=null; char[] buf=new char[1024]; try { FileReader f=new FileReader(fliename); // InputStreamReader f=new InputStreamReader(new FileInputStream(fliename),"UTF-8"); while(f.read(buf)>0){ strbf.append(buf); } s=strbf.toString(); return s; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }