关于字节流的写入与读取

baoliang0624 2011-10-01 01:49:52
以下两个类,第一个是向文件写入字节信息,第二个则读取该文件的内容

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□!

为何第二个类读取结果出现异常,大虾们知道问题在哪?请解答一下,谢谢!
...全文
247 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
baoliang0624 2011-10-01
  • 打赏
  • 举报
回复
其实是在重新学JAVA遇到的点小问题咯,谢谢以上两位的回复。
风尘中国 2011-10-01
  • 打赏
  • 举报
回复
这个问题的原因主要是你用的是DataOutputStream的writeChars()这个API像文件当中写入数据,这个API是为字符数组写数据服务的,每个char元素写入到文件之后会有默认的分隔符(实质就是数值是0的数据),这个分隔符造成了你再读取文件的字符串的时候出现你上面的情况

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

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

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();
}
}
}


打油的程序员 2011-10-01
  • 打赏
  • 举报
回复
你应该去了解什么是utf编码 什么是gbk,gb2312编码


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();
}
}

}


62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧