各位高手,我刚学输入输出流,我用RandomAccessFile输出一串字符到一个txt文件,为什么前面会有一个乱码符号?
代码:
import java.io.*;public class RandomAccessFileTest
{
public static void main(String[] args)
{
try
{
String str="nihao wohao 大家好";
RandomAccessFile out=new RandomAccessFile("555.txt","rw");
out.writeUTF(str);
out.close();
}
catch(IOException e)
{}
}
}
结果: nihao wohao 大家好
请问前面怎么会多出一个空格和一个倒T字
代码:
import java.io.*;public class RandomAccessFileTest
{
public static void main(String[] args)
{
try
{
String str="nihao wohao 大家好";
RandomAccessFile out=new RandomAccessFile("555.txt","rw");
out.writeUTF(str);
out.close();
}
catch(IOException e)
{}
}
}
结果: nihao wohao 大家好
请问前面怎么会多出一个空格和一个倒T字
writeUTF
public final void writeUTF(String str)
throws IOException使用 modified UTF-8 编码以与机器无关的方式将一个字符串写入该文件。
首先,把两个字节从文件的当前文件指针写入到此文件,类似于使用 writeShort 方法并给定要跟随的字节数。此值是实际写出的字节数,而不是该字符串的长度。在该长度之后,按顺序输出该字符串的每个字符,并对每个字符使用 UTF-8 修改版编码。
import java.io.*; public class Test
{
public static void main(String[] args)
{
try
{
String str="nihao wohao 大家好";
RandomAccessFile out=new RandomAccessFile("c:/555.txt","rw");
out.write(str.getBytes("GBK"));
out.close();
}
catch(IOException e)
{}
}
}
源码里有中文,跟编译时制定的字符集有关
上面代码在我这里通过