RandomAccessFile解决中文乱码
(2016-07-27 21:07:36)
标签:
java解决中文乱码 |
分类: 解决中文乱码 |
// 如何进行编码格式的转换
public class RandomAccessFileTest {
public static void writeFile() {
RandomAccessFile rout = null;
try {
rout = new RandomAccessFile("dd.txt", "rw");
rout.seek(rout.length()); // 设置写入的位置
for (int i = 1; i <= 10; i++) {
// RandomAccessFile不支持GBK编码格式,而仅仅支持ISO8859-1格式的字符编码
String str = i
+ ".此类的实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型 byte
数组\r\n";
// 需要进行编码格式的转换,把GBK编码格式转换为ISO8859-1
String temp = new String(str.getBytes("GBK"),
"ISO8859-1");
rout.writeBytes(temp);
}
System.out.println("文件写入成功");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rout != null) {
rout.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void readFile() {
RandomAccessFile rin = null;
try {
rin = new RandomAccessFile("dd.txt", "r");
String str = null;
while ((str = rin.readLine()) != null) {
// 把ISO8859-1格式转换为GBK格式
String temp = new String(str.getBytes("ISO8859-1"),
"GBK");
System.out.println(temp);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rin != null) {
rin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// writeFile();
readFile();
}
}