读二进制文件,报错

tjficcbw 2010-05-09 08:19:30

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

/* @author tianzitian
* @since 2010.5.8
* @description read and write stream for binary file。
*/
public class BinaryReadWrite {
private DataInputStream dis = null;
private DataOutputStream dos = null;
private String s_FilePath = "d:/bin.dat";
private byte[] m_datapadding = { 0x00 };

// private byte[] m_datapadding = { 0x00 }; // 填充空白,以补足字节位数.

public BinaryReadWrite() {
// TODO Auto-generated constructor stub
init();
}

private void init() {
try {
if (!new File(s_FilePath).exists()) {
new File(s_FilePath).createNewFile();
}
dis = new DataInputStream(new FileInputStream(new File(s_FilePath)));
dos = new DataOutputStream(new FileOutputStream(
new File(s_FilePath)));
} catch (Exception e) {
e.printStackTrace();
}
}

public void writeBinaryStream(String Pwd1) {
try {
if (dos != null) {
dos.writeUTF(Pwd1);
dos.write(m_datapadding);
dos.flush();
dos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

public String readBinaryStream() {
String Pwd = null;
try {


Pwd = dis.readUTF();

} catch (Exception e) {
e.printStackTrace();
}
return Pwd;
}

public static void main(String[] args) throws IOException {
BinaryReadWrite bin = new BinaryReadWrite();
// bin.writeBinaryStream("abc");
String Pwd = bin.readBinaryStream();
System.out.println(Pwd);
}
}



不注释倒数第5行是写入后读取,
注释了只是读取,这时报错,
连写带读可以光读就不行,不知如何改动,谢谢了
...全文
126 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
lfssay 2010-05-11
  • 打赏
  • 举报
回复
这个好像是文件格式的问题

在你没有注释那句的时候,是先写入文件一个UTF格式的,后来读UTF 肯定没问题

但是没有那句后,就只是在一个未知格式的文件里面读了,昨天我也试过这个问题,也请教了高手,都是说的在不同系统下文件里面的字符编码差别很大,这样你读的就不一定是个UTF编码的了
liboofsc 2010-05-10
  • 打赏
  • 举报
回复
报的什么异常应该说一下。
lfssay 2010-05-10
  • 打赏
  • 举报
回复
占个位置

继续问这个问题哈
bawgiitx 2010-05-10
  • 打赏
  • 举报
回复

dos.writeUTF(Pwd1);
dos.write(m_datapadding);////
justlearn 2010-05-09
  • 打赏
  • 举报
回复
如果不加,你就得注释掉main方法那句的同时,把dos相关的都注释掉
justlearn 2010-05-09
  • 打赏
  • 举报
回复
dos = new DataOutputStream(new FileOutputStream(
new File(s_FilePath),true));
改成这样就可以了,你打开outputstream的时候把文件清空了,所以造成读不到数据了
tjficcbw 2010-05-09
  • 打赏
  • 举报
回复
我的程序,主函数里是一行是写,一行是读,能写也能读,但注释写只读是报错
justlearn 2010-05-09
  • 打赏
  • 举报
回复
你用了dis.readUTF();
读取的是UTF,你写入读取都是用的UTF,所以不会错。
但是如果你文件里本来不是有效的UTF格式就会报错。
看看是否抛的UTFDataFormatException,然后检查你的文件

62,614

社区成员

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

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