读文件乱码是因为在RandomAccessFile下用readLine的方式会自动将编码变成ISO-8859-1。所以只要按照如下方式即可RandomAccessFile fl=new RandomAccessFile(file,"rw"); while(fl.getFilePointer() System.out.println( new String(fl.readLine().getBytes("ISO-8859-1"), "gb2312")); //gb2312是你文本编码格式。 } 使用RandomAccessFile向数据库写入中文的时候, *使用write(String.getBytes()), 能够正常写入 *使用writeBytes(String), writeChars(String), writeUTF(String)均产生乱码。 import java.util.*; import java.io.*;public class Wenjian { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub double[] b = new double[5]; double[] d = new double[5]; System.out.println("请输入5个浮点数"); @SuppressWarnings("resource") Scanner a = new Scanner(System.in); for (int i = 0; i < 5; i++) b[i] = a.nextDouble(); RandomAccessFile rand = new RandomAccessFile("D:\\aaa.txt", "rw"); /*while(rand.getFilePointer()>0){ System.out.println( new String(rand.readLine().getBytes("ISO-8859-1"), "gb2312")); //gb2312是你文本编码格式。 }*/ for (int i = 0; i < b.length; i++){ System.out.println(b[i]); rand.write((b[i]+"").getBytes()); rand.writeBytes(" "); } @SuppressWarnings("resource") Scanner scanner = new Scanner(new FileInputStream("D:\\aaa.txt")); while (scanner.hasNextDouble()) { for (int i = 0; i < 5; i++) d[i] = scanner.nextDouble(); } Arrays.sort(d); for (int i = d.length - 1; i > 0; i--) System.out.print(" " + d[i]); for (int i = 0; i < d.length; i++) rand.writeDouble(d[i]); rand.close(); }}
while(rand.getFilePointer()>0){ System.out.println( new String(rand.readLine().getBytes("ISO-8859-1"), "gb2312")); //gb2312是你文本编码格式。
while(fl.getFilePointer()
System.out.println( new String(fl.readLine().getBytes("ISO-8859-1"), "gb2312")); //gb2312是你文本编码格式。 }
使用RandomAccessFile向数据库写入中文的时候, *使用write(String.getBytes()), 能够正常写入 *使用writeBytes(String), writeChars(String), writeUTF(String)均产生乱码。
import java.util.*;
import java.io.*;public class Wenjian { public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
double[] b = new double[5];
double[] d = new double[5];
System.out.println("请输入5个浮点数");
@SuppressWarnings("resource")
Scanner a = new Scanner(System.in);
for (int i = 0; i < 5; i++)
b[i] = a.nextDouble();
RandomAccessFile rand = new RandomAccessFile("D:\\aaa.txt", "rw");
/*while(rand.getFilePointer()>0){
System.out.println( new String(rand.readLine().getBytes("ISO-8859-1"), "gb2312")); //gb2312是你文本编码格式。 }*/
for (int i = 0; i < b.length; i++){
System.out.println(b[i]);
rand.write((b[i]+"").getBytes());
rand.writeBytes(" ");
}
@SuppressWarnings("resource")
Scanner scanner = new Scanner(new FileInputStream("D:\\aaa.txt"));
while (scanner.hasNextDouble()) {
for (int i = 0; i < 5; i++)
d[i] = scanner.nextDouble();
}
Arrays.sort(d);
for (int i = d.length - 1; i > 0; i--)
System.out.print(" " + d[i]);
for (int i = 0; i < d.length; i++)
rand.writeDouble(d[i]);
rand.close();
}}
while(rand.getFilePointer()>0){
System.out.println( new String(rand.readLine().getBytes("ISO-8859-1"), "gb2312")); //gb2312是你文本编码格式。
}这段代码要放开