自定义文件类型的保存和读出
文件类型是文件的一种格式。我们常见格式,如:".txt"、".exe"。它们指的是文件的一种保存方式,并且我们每次读出其中的消息的时候也会按照这一种相应的方式。
老师告诉我们这些格式都是由大公司们自己确定的,然后让全球来遵守。于是,下面我就带着大家来创建自己的个人文件格式,由自己来遵守。当我们的影响力超过了乔布斯的时候,这格式也会叫全球共同认可滴。
创建的一种新的文件格式“.hhf”——文件的前面部分为文件的说明文件名,文件的大小;文件的后面部分为文件的内容。
创建这种新文件格式还应该包含两个部分——文件的创建保存,和文件的读取。
/*
* 将二维数组中的数据保存到指定的文件中 (文件头信息 文件大小宽高 文件数据( 二维数组中的数据))
*
* @param array 要保存的二位数组
*
* @param path 存入的文件路径
*/
public void saveFile(int[][] array, String path) {
try {
// 文件输出流
FileOutputStream fos = new FileOutputStream(path);
// 将文件输出流包装成可写基本数据类型的数据流
DataOutputStream dos = new DataOutputStream(fos);
// 写文件头信息
dos.writeByte(72);
dos.writeByte(72);
dos.writeByte(70);
// 宽度和高度
dos.writeInt(array.length);
dos.writeInt(array[0].length);
// 写文件数据
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int num = array[i][j];
dos.writeInt(num);
}
}
// 强制输出数据
dos.flush();
dos.close();
} catch (Exception ef) {
ef.printStackTrace();
}
下一个就会是文件的读取函数——注意文件的读取格式和上一个函数文件的保存格式高度一致。
/**
* 打开指定的文件
*
* @param path
* 文件的路径
* @return 将文件中的数据装在二维数组中返回
*/
public int[][] openFile(String path) {
try {
// 文件输入流
FileInputStream fis = new FileInputStream(path);
// 包装
DataInputStream dis = new DataInputStream(fis);
// 读文件头
byte b1 = dis.readByte();
byte b2 = dis.readByte();
byte b3 = dis.readByte();
System.out.println("文件头:" + b1 + b2 + b3);
// 读取宽度和高度
int width = dis.readInt();
int height = dis.readInt();
System.out.println("文件大小:" + width + height);
// 准备接收数据
//int[][] array = new int[height][width];
// 读数据
for (int i = 0; i < saveColor.length; i++) {
for (int j = 0; j < saveColor[i].length; j++) {
int num = dis.readInt();
saveColor[i][j] = num;
}
}
return saveColor;
} catch (Exception ef) {
ef.printStackTrace();
}
return null;
}
到这里,相信各位对文件格式的概念,大概有了新的理解吧^_^。