我要对比两个txt文档的内容,如果有不相同的词,就把第一个文档中的这个词拷贝到新的txt文档中,使用RandomAccessFile方便对文件的定位,可却导致输出乱码,请问怎么办?部分代码如下:
RandomAccessFile in1 = 
new RandomAccessFile("result.txt", "r");
RandomAccessFile in2= 
         new RandomAccessFile("result1.txt", "r");
 
PrintWriter out= 
new PrintWriter(new FileWriter("out.txt", true));

String line1, line2;
char[] buffer1= new char[50];
char[] buffer2= new char[50];
int flag = 0;

while((line1 = in1.readLine()) != null){
while((line2 = in2.readLine()) != null){
// in2.(0);
for(int i = 0; i < line1.length() 
    && i < line2.length(); i++){
buffer1[i]= line1.charAt(i);
buffer2[i]= line2.charAt(i);

if (buffer1[i] == ','){
if (buffer2[i] == ','){
for (int j = i; j < 50; j++)
buffer1[j] = buffer2[j] = '\n';
// String.valueOf(buffer1);
// String.valueOf(buffer2);
String s1= new String(buffer1);
String s2= new String(buffer2);
                            boolean tag;
                            tag= s1.equals(s2);
                            if (tag){
                             flag = 1;
                            }
    }
break;
}
else{
if( buffer2[i] == ',')
break;
}
if (flag == 1){
break;
}
}
}
if (flag == 1){
flag = 0;
in2.seek(0);
}
else if (flag == 0){
out.write(line1);
out.write('\n');
                in2.seek(0);
}
}
in1.close();
in2.close();
out.close();

解决方案 »

  1.   

    你读出来的是byte, 想输出来字符,是要转换的,或指定字符编码
      

  2.   

    这是JDK的文档对RandomAccessFile的一句说明:A random access file behaves like a large array of bytes stored in the file system.你可以用这个类的write的各种方法()向文件里写写看,后然用记事本看内容,你会发现里面根本就不是文本文件(除了英文),程序如下:    try {
          DataOutputStream out2 = new DataOutputStream(
            new BufferedOutputStream(
              new FileOutputStream("Data.txt")));
          out2.writeDouble(3.14159);
          out2.writeUTF("哈哈哈");
          out2.writeDouble(1.41413);
          out2.writeUTF("Square root of 2");
          out2.close();
          DataInputStream in5 = new DataInputStream(
            new BufferedInputStream(
              new FileInputStream("Data.txt")));
          // Must use DataInputStream for data:
          System.out.println(in5.readDouble());
          // Only readUTF() will recover the
          // Java-UTF String properly:
          System.out.println(in5.readUTF());
          // Read the following double and String:
          System.out.println(in5.readDouble());
          System.out.println(in5.readUTF());
        } catch(EOFException e) {
          throw new RuntimeException(e);
        }所以说,这个类明显不适合你的需求,你还是用其他的类如各种Writer来进行比较吧