请问:如何处理RandomAccessFile中的中文写入变成乱码的问题(50分)

  • 主题发起人 主题发起人 tominsight
  • 开始时间 开始时间
T

tominsight

Unregistered / Unconfirmed
GUEST, unregistred user!
用RandomAccessFile的writeChars写入中文字符串时显示乱码。请问如何解决。
(因为可用积分只有57了,只能给到50。抱歉)
测试程序代码如下:
import java.io.*;
public class test {
static String fileName = "Ran.txt";
static String tt = "你的IP是这个样子.";
static String ttt = "你";
public static void main(String[] args) {
try {
System.out.println(tt);
sayHello();
appendHi();
readGreeting();
} catch (IOException x) {
System.out.println(x.getMessage());
}
}
public static void sayHello() throws IOException {
DataOutputStream ds = null;
try {
File f = new File(fileName);
FileOutputStream out = new FileOutputStream(f);
ds = new DataOutputStream(out);
ds.writeBytes("hello!");
} finally {
if (ds != null)
ds.close();
}
}
public static void appendHi() throws IOException {
RandomAccessFile out = null;
try {
File f = new File(fileName);
out = new RandomAccessFile(f, "rw");
out.seek(out.length());
out.writeChars(tt);
} finally {
if (out != null)
out.close();
}
}
public static void readGreeting() throws IOException {
RandomAccessFile in = null;
try {
File f = new File(fileName);
in = new RandomAccessFile(f, "r");
String s = in.readLine();
System.out.println(s);
} finally {
if (in != null)
in.close();
}
}
}
 
把out.writeChars(tt);改为out.writeUTF(tt);
 

Similar threads

后退
顶部