今天学习了使用Java读写二进制文件,略有所得,不错!
先来补课:
代码如下:
写二进制文件:
import java.io.*;
public class BinFileWrite{
public static void main(String[] args) throws Exception{
writeFile();
System.out.println("done.");
}
public static void writeFile() {
FileOutputStream fos = null;
DataOutputStream dos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("c:/temp/tbd.dat"); // 节点类
bos = new BufferedOutputStream(fos); // 装饰类
dos = new DataOutputStream(bos); // 装饰类
dos.writeInt(2020);
dos.writeUTF("is a new start!");
dos.writeInt(2050);
dos.writeUTF("is full of hope!");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
dos.close(); // 关闭最后一个类,会将所有的底层流都关闭
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
文件写入(创建)成功后,使用Notepad++打开后,发现数字部分不可读,这正说明了二进制文件并不是记事本等文本处理软件的处理对象。
解铃还需系铃人,且看读二进制文件的代码:
import java.io.*;
public class BinFileRead{
public static void main(String[] args) throws Exception{
readFile();
}
public static void readFile() {
//try-resource 语句,自动关闭资源
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("c:/temp/tbd.dat")))) {
String b, d;
int a, c;
a=dis.readInt();
b=dis.readUTF();
c=dis.readInt();
d=dis.readUTF();
System.out.println("a: "+a);
System.out.println("b: "+b);
System.out.println("c: "+c);
System.out.println("d: "+d);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
运行结果:
a: 2020 b: is a new start! c: 2050 d: is full of hope!
|
不难发现,为了正确读入二进制文件中的内容, 需要知道写入时的顺序及内容。如,写入的内容为:
dos.writeInt(2020);
dos.writeUTF("is a new start!");
dos.writeInt(2050);
dos.writeUTF("is full of hope!");
则,读取时的语句与上述过程是依次对应的:
a=dis.readInt();
b=dis.readUTF();
c=dis.readInt();
d=dis.readUTF();