日期:2014-05-20  浏览次数:20732 次

关于字节流的写入与读取
以下两个类,第一个是向文件写入字节信息,第二个则读取该文件的内容

public class WriteBytesToFile {
public static void main(String[] args) {
 
String v5 ="Hello,java world!";
try{
File fileName =new File("D:\\data.dat");
DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
output.writeChars(v5);
  output.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
  }

public class ReadBytesFromFile {
  public static void main(String[] args){

try{
File fileName = new File("d:\\data.dat");
DataInputStream input = new DataInputStream(new FileInputStream(fileName));
byte[] buff =new byte[34];
input.read(buff);
String v5 = new String(buff);
System.out.println(v5);

}catch(FileNotFoundException exp){
exp.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}

}

运行第一个类,生成文件,内容为字节形式的"Hello,java world!"(记事本打开可以看到)
但运行第二个类读取的内容却是□H□e□l□l□o□,□j□a□v□a□ □w□o□r□l□d□!

为何第二个类读取结果出现异常,大虾们知道问题在哪?请解答一下,谢谢!

------解决方案--------------------
你应该去了解什么是utf编码 什么是gbk,gb2312编码
Java code


public class WriteBytesToFile {
    public static void main(String[] args) {

    String v5 = "Hello,java world!";
    try {
        File fileName = new File("c:\\data.dat");
        DataOutputStream output = new DataOutputStream(
            new FileOutputStream(fileName));
        output.write(v5.getBytes());//应该转为字节数组写进去
        output.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    }
}

public class ReadBytesFromFile {
    public static void main(String[] args) {

    try {
        File fileName = new File("c:\\data.dat");
        DataInputStream input = new DataInputStream(new FileInputStream(
            fileName));
        //byte[] buff =new byte[34];//34太大了
        byte[] buff = new byte[(int) fileName.length()];//34太大了,所以打印出无效信息

        input.read(buff);
        String v5 = new String(buff);
        System.out.println(v5);

    } catch (FileNotFoundException exp) {
        exp.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    }

}

------解决方案--------------------
这个问题的原因主要是你用的是DataOutputStream的writeChars()这个API像文件当中写入数据,这个API是为字符数组写数据服务的,每个char元素写入到文件之后会有默认的分隔符(实质就是数值是0的数据),这个分隔符造成了你再读取文件的字符串的时候出现你上面的情况

要避免这种情况,可以将原来的文件输出流用writeBytes(String)替代,这样就没有你说的情况了

如果你只是想要对文本文件写入一些数据,用FileWriter可能更快捷一些
Java code

import java.io.FileOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;

public class WriteBytesToFile {
    public static void main(String[] args) {

        String v5 ="Hello,java world!";
        try{
            File fileName =new File("D:\\data.dat");
            DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
//            output.writeChars(v5);
            output.writeBytes(v5);
            output.close();
        }catch(IOException ex){
            ex.printStackTrace();
        }
    }
}