java中文件的读写经常使用byte,但使用经常使用short类型,所以需要使用两种类型转换,byte8位,shot16位,需要进行移位拼接操作。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class TestMain {
public static void main(String[] args)
{
short[] st_1 = new short[2];
st_1[0] = 127;
st_1[1] = 128;
byte[] bt_1 = new byte[4];
short[] st_2 = new short[2];
byte[] bt_2 = new byte[4];
System.out.println("st_1="+String.valueOf(st_1[0])+String.valueOf(st_1[1]));
for(int i = 0 ;i < 2;i++)
{
bt_1[i*2] = (byte)(st_1[i]);
bt_1[i*2+1] = (byte)(st_1[i]>>8);
}
try {
File fl = new File("test.txt");
if(fl.exists());
else
{
fl.createNewFile();
}
FileOutputStream fStream = new FileOutputStream("test.txt");
fStream.write(bt_1);
FileInputStream fInputStream = new FileInputStream(fl);
while(fInputStream.read(bt_2) != -1)
{
}
} catch (Exception e)
{
// TODO: handle exception
}
for(int i = 0;i < 2;i++)
{
st_2[i] = (short)((bt_2[i*2+1]<<8)|(bt_2[i*2]&0xff));
}
System.out.println("st_2="+String.valueOf(st_2[0])+String.valueOf(st_2[1]));
}
}
输出结果
st_1=127128
st_2=127128