Java错误地读取ANSI文件

时间:2011-05-04 14:18:02

标签: java ansi java.util.scanner

我尝试使用以下两种方式在Java中读取ANSI编码的阿拉伯文件

    Scanner scanner = null;
    try {
           scanner = new Scanner(new File("test/input.txt"), "ISO-8859-6");

    while (scanner.hasNextLine()) {
        String input =scanner.nextLine();
        processString(input);   
    }

我还尝试使用默认编码进行读取(即我省略了“ISO-8859-6”)

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

试试这段代码:

 public static void transform(File source, String srcEncoding, File target,       String tgtEncoding) throws IOException {
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(source), Charset.forName(srcEncoding)));
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding));
        char[] buffer = new char[16384];
        int read;
        while ((read = br.read(buffer)) != -1) {
            bw.write(buffer, 0, read);
        }
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } finally {
            if (bw != null) {
                bw.close();
            }`enter code here`
        }
    }
}

答案 1 :(得分:0)

看看这个:

       private static final String FILENAME = "/Users/jucepho/Desktop/ansi.txt";

   public static void main(String[] args) {
            BufferedReader br = null;
            FileReader fr = null;
            try {
                fr = new FileReader(FILENAME);
                br = new BufferedReader(fr);
                String sCurrentLine;
                br = new BufferedReader(new FileReader(FILENAME));
                while ((sCurrentLine = br.readLine()) != null) {
                    System.out.println(sCurrentLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)
                        br.close();
                    if (fr != null)
                        fr.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

此文件包含此字符http://www.alanwood.net/demos/ansi.html