Java ASCII输出到文件

时间:2012-02-02 21:17:22

标签: java file ascii

当我尝试将ASCII值输出到文件时,使用某些字符会返回错误的值。例如:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;

    public class test {
    public static void main(String args[]){
                                  //Supposed to:
        writeFile("./test.txt"); //write ASCII 147
        readFile("./test.txt"); //read ASCII 147
    }

    public static boolean writeFile(String path){
        try{
            PrintWriter fo = new PrintWriter(new FileOutputStream(new File(path)));
            fo.print((char) 147); //WRITES "?" TO FILE (ASCII 63, NOT 147)
            fo.close();
        }catch(Exception e){
            return true;
        }
        return false;
    }

    public static boolean readFile(String path){
        try {
            BufferedReader fi = new BufferedReader(new FileReader(path));
            char c[] = fi.readLine().toCharArray();
            System.out.println((int) c[0]); //OBVIOUSLY PRINTS 63 INSTEAD OF 147
            fi.close();
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}

我做错了什么?任何帮助都会很棒。感谢。

2 个答案:

答案 0 :(得分:6)

ASCII中没有“字符147”这样的东西。

你应该给出一个可以代表你感兴趣的角色的特定编码 - UTF-8通常是一个不错的选择 - 并且使用相同的编码进行读写。

不幸的是,FileWriterFileReader不允许您指定编码,因此您需要将FileOutputStreamFileInputStream包含在OutputStreamWriter中, InputStreamReader

import java.io.*;
import java.nio.charset.*;

public class Test {

    private static Charset UTF8 = Charset.forName("UTF-8");

    public static void main(String args[]) throws IOException {
        writeFile("./test.txt");
        readFile("./test.txt");
    }

    public static void writeFile(String path) throws IOException {
        Writer writer = new OutputStreamWriter(new FileOutputStream(path), UTF8);
        try {
            writer.write((char) 147);
        } finally {
            writer.close();
        }
    }

    public static void readFile(String path) throws IOException {
        Reader reader = new InputStreamReader(new FileInputStream(path), UTF8);
        try {
            int c = reader.read();
            System.out.println(c);
        } finally {
            reader.close();
        }
    }
}

答案 1 :(得分:0)

有些语言会混淆字符和八位字节类型(C和C ++是值得注意的例子。)Java char类型是隐式UTF-16,ASCII必须使用byte类型表示。请参阅here进行比较。有关Java编码指南,请参阅here