Linda_Lindaaaa
2015-04-26 08:02
采纳率: 64.7%
浏览 4.1k
已采纳

这是我整理的从文件夹中读取所有txt文件,并读取里面内容的java程序,问什么读出来的汉字是乱码?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;

public class Evaluation /*implements Runnable*/{
private File file = null;

public static void main(String[] args) throws Exception{ 

    String FILE_IN = "E:\\myImage";
    File f = new File(FILE_IN);
    List<String> list = new ArrayList<String>();
    list = getFileList(f);
    String text=null;

    System.out.println(list.size());

    for (String l : list) {

   text=getTextFromTxt(l);
   System.out.println(text.toString());
    }  
}


public static List<String> getFileList(File file) {

    List<String> result = new ArrayList<String>();

    if (!file.isDirectory()) {
        //System.out.println(file.getAbsolutePath());
        result.add(file.getAbsolutePath());
    } else {
        File[] directoryList = file.listFiles(new FileFilter() {
            public boolean accept(File file) {
                if (file.isFile() && file.getName().indexOf("txt") > -1) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        for (int i = 0; i < directoryList.length; i++) {
            result.add(directoryList[i].getPath());
        }
    }

    return result;
}
public static String getTextFromTxt(String filePath) throws Exception {   

    FileReader fr = new FileReader(filePath);   
    BufferedReader br = new BufferedReader(fr);   
    StringBuffer buff = new StringBuffer();   
    String temp = null;   
    while ((temp = br.readLine()) != null) {   
        buff.append(temp + "\r\n");   
    }   
    br.close();   
    return buff.toString();   
}   

}

 输出结果:
 4
鍘嬬缉璁?鏂囦欢鍚嶏細88073
鏂囨湰妗嗘暟锛?
杈撳嚭瀛楃鏁帮細3
鏃堕棿:109.71428571428572



璧甸兘鎶?鏂囦欢鍚嶏細87769
鏂囨湰妗嗘暟锛?
杈撳嚭瀛楃鏁帮細3
鏃堕棿:117
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新