0 引言
最近老师让写一个程序,作为学习JAVA的练习。目的在于:将一个二进制文件中的数据读取出来,其中数据包括点的位置信息和压力值及状态。将这些数据画作图像的形式展示。
本小程序分为以下几部分:
(1)读取二进制文件;其中需要考虑二进制文件读出来的是十进制数,需要将二个字节合成一个short型,并转换为int型值。
(2)画图;根据读取到的点的信息,循环,如果状态是画,则将该点与上一点相连;
1 读取二进制文件
所有的输入流类都是抽象类InputStream或Reader的子类。本文主要使用其中的FilterInputStream子类中的DataInputStream和BufferedInputStream这两个子类。
1.1 DataInputStream
构造函数为:
DataInputStream(InputStream in)
Creates a DataInputStream that uses the specified underlying InputStream.
使用基础类InputStream构造DataInputStream
方法主要有,见下表
本文使用readFully(byte[] b)方法读取所有的字节信息。
代码示例如下:
DataInputStream dis = null;
dis = new DataInputStream(new FileInputStream ("./test.txt"));
byte []b = new byte [1024];
dis.read(b);
文件的所有信息都会存储在定义的byte数组中。
1.2 BufferedInputStream
构造函数如下:
BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
BufferedInputStream(InputStream in, int size)
Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use.
方法主要有,见下表
主要使用read(byte [], off, len)方法读取文件信息。方法available()返回文件的字节数;
示例代码如下:
BUfferedInputStream bis = null;
bis = new BufferedInputStream(new fileInputStream("./test.txt"));
int len = bis.available();
byte []b = new byte[len];
bis.read(b, 0, len);
byte数组中将存放文件的所有信息。
1.3 处理数据
根据以上两种方法获取了数据,接下来将对数据转换成int型。
由于buff数组中存放的是一个字节一个字节的,故将两个字节组合即可。
代码如下:
int x = (buff[0] & 0xff) | (buff[1] & 0xff) << 8;
int y = (buff[2] & 0xff) | (buff[3] & 0xff) << 8;
以上是小端模式(低地址中存放的是字数据的低字节,高地址存放的是字数据的高字节)的转换,大端(与小端相反)的话直接调换一下就行。
2 画图
采用Graphics2D进行画图,使用BufferedImage创建画,并通过方法getGraphics()返回2D图像。
// create a BufferedImage with the size of (width, height)
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// to draw strokes, we need a Graphics2D - correlated with BufferedImage
Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
// set the background to be WHITE
graphics2D.setBackground(Color.WHITE);
graphics2D.clearRect(0, 0, width, height);
// set width and color for lines
graphics2D.setPaint(Color.BLACK);
graphics2D.setStroke(new BasicStroke(3));
2.1 将所有点连接成线
判断该点的状态是否是画,及下一个点是否是画,然后再连线
int pos;
boolean bDrawing = false;
int xPrev=-1, yPrev=-1;
for( pos = 4; pos + 7 <= nLength ; pos += 7)
{
byte status = buffer[pos];
int x = ((buffer[pos+1]&0xff) | ((buffer[pos+2]&0xff) << 8)) / 10;
int y = ((buffer[pos+3]&0xff) | ((buffer[pos+4]&0xff) << 8)) / 10;
if( bDrawing ) {
if(status == 0x11) {
graphics2D.drawLine(xPrev, yPrev, x, y);
xPrev = x;
yPrev = y;
}
else {
bDrawing = false;
}
}
else {
if(status == 0x11) {
bDrawing = true;
xPrev = x;
yPrev = y;
}
else {
// floating
}
}
}
3 结果
4 总结
任重而道远,老师还是最牛逼的!