我想知道当我PrintWriter用于写入文件时。它将用文件或二进制格式的ASCII码写入?谢谢。
3 回答
AWriter写入字符,因此最终在文件中的二进制数据取决于编码。
例如,如果您使用 UTF-16 等 16 位编码,那么每个 ASCII 字节都会有一个额外的零字节:
public class TestWriter
{
public static void main(String[] args)
throws UnsupportedEncodingException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final OutputStreamWriter out = new OutputStreamWriter(baos, "UTF-16");
final PrintWriter writer = new PrintWriter(out);
writer.printf("abc");
writer.close();
for (final byte b : baos.toByteArray())
{
System.out.printf("0x%02x ", b);
}
System.out.printf("\n");
}
}
打印0xfe 0xff 0x00 0x61 0x00 0x62 0x00 0x63。
You can write most ASCII letters as text or binary and you will get the same outcome with most characters encodings. Two of the ASCII characters have a special meaning in text files, are newline \n and carriage return \r. This means that if you have text file and you want to write a String which contains these characters it can be hard or impossible for the reader to distinguish between end-of-line in the text file e.g. println() and end-of-line you put in a String e.g. print("1\n2\n3\n")
它将输出字符数据。但这可能超出了 ASCII 集,它只包含 128 个字符,其中前 32 个是特殊控制字符。