java 文件问题

来源:百度知道 编辑:UC知道 时间:2024/09/28 11:06:19
import java.io.*;

public class file9
{
public static void main(String[] args)throws Exception
{
String st;
File f=new File("f:\\11.dat");
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dos=new DataOutputStream(fos);
try
{
dos.writeChars("明天要下雨了。");
dos.writeUTF("明天要下雨了。");
dos.writeUTF("明天要下雨了。");
dos.writeUTF("明天要下雨了。");
}
catch(Exception e)
{}
dos.close();
}
}

f盘下11.txt中并未出现预期内容,为何?
import java.io.*;

public class file9
{
public static void main(String[] args)throws Exception
{
String st;
File f=new File("f:\\11.dat"); //此处改为dat-->txt
FileOutputStream fos=new FileOutputStream(f);
DataOutp

第一dos.writeChars("明天要下雨了。"); 将出现乱码,字符集的问题,意料之中。
第二出乎意料的是dos.writeUTF("明天要下雨了。"); 多了几个字符,查API发现:

writeUTF
public final void writeUTF(String str)
throws IOException以与机器无关方式使用 UTF-8 修改版编码将一个字符串写入基础输出流。
首先,通过 writeShort 方法将两个字节写入输出流,表示后跟的字节数。该值是实际写出的字节数,不是字符串的长度。根据此长度,使用字符的 UTF-8 修改版编码按顺序输出字符串的每个字符。如果没有抛出异常,则计数器 written 增加写入输出流的字节总数。该值至少是 2 加 str 的长度,最多是 2 加 str 的三倍长度。
所以也是正常现象。
第三你可以使用dos.write("明天要下雨了".getBytes("UTF-8"));来输出,这样就不会多出字符了