51,411
社区成员
发帖
与我相关
我的任务
分享
package jp19052401;
import java.io.*;
public class MyClass {
public static byte makeByte(int ASeq,int ACount)
{
return (byte) (((ASeq & 0x000f) <<4) | ACount & 0x000f & 0x0f);
}
public static int[] spliteByte(byte AValue)
{
int ret[]=new int[2];
ret[0]=(AValue & 0xf0 ) >> 4 ;
ret[1]=AValue & 0x0f;
return ret;
}
public static byte[] spliteInt(int AValue)
{
byte ret[]=new byte[2];
ret[0]=(byte)((AValue & 0x0000fffff & 0xff00) >> 8);
ret[1]=(byte)(AValue & 0x0000ffff & 0x00ff);
return ret;
}
public static int makeWord(byte l,byte h)
{
return (l | (h << 8));
}
public static void strToDatFile(StringBuilder str,int divLen)
{
int count=str.length()/divLen;
if(str.length() % 2 !=0) count++;
if(count>7) return;//makeByte(7,7),7之后的数会超出byte范围
int seq=1;
StringBuilder sValue=new StringBuilder();
while (str.length()>0)
{
if(str.length()>divLen)
sValue.append(str.subSequence(0, divLen));
else sValue.append(str.subSequence(0, str.length()));
//System.out.println(sValue);
try {
FileOutputStream fs=new FileOutputStream("./"+Integer.toString(seq)+".dat",false);
byte b=makeByte(seq,count);
byte[] ba=new byte[2];
ba=spliteInt(sValue.length());
fs.write(b);
fs.write(ba[0]);//数据长度高字节
fs.write(ba[1]);//数据长度低字节
fs.write(sValue.toString().getBytes());
fs.flush();
fs.close();
}
catch(IOException e)
{
e.printStackTrace();
}
str.delete(0, divLen);
seq++;
sValue.setLength(0);
}
}
public static void datFileRead(String filename)
{
try {
FileInputStream fs=new FileInputStream(filename);
byte[] b=new byte[3];
fs.read(b, 0, 3);
int[] iA=new int[2];
iA=spliteByte(b[0]);
System.out.println(iA[0]);//Seq
System.out.println(iA[1]);//Count
int len=makeWord(b[2], b[1]);//b[2]是低字节,b[1]是高字节
byte sValue[]=new byte[len];
fs.read(sValue);
fs.close();
String s=new String(sValue);
System.out.println(s);
System.out.println();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//写入
StringBuilder sb=new StringBuilder("2UOZVPJ0C7ABC");
strToDatFile(sb,5);
//读取
datFileRead("./1.dat");
datFileRead("./2.dat");
datFileRead("./3.dat");
}
}