请教一个java中有关字符串生成二进制文件的问题

现在有这样一个字符串:“ 10 2 1 0 1 ”如何将这个字符串生成一个二进制文件,用ultraedit打开二进制文件的时候,第一个字节表示10,第二个字节表示2,以此类推。用java编写。。。

第1个回答  2016-05-04
string hexString= "1002010001";
byte[] data = string2Byte(hexString);
ByteBuffer buffer=ByteBuffer.allocate(5);
        buffer.put(data);
        buffer.flip();
        File file = new File("d:/1.dat");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(buffer.array());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
public static byte[] string2Byte(String hexString) {
   hexString = hexString.toUpperCase();
   char[] chars = hexString.toCharArray();
   int len = chars.length >> 1;
   byte[] bytes = new byte[len];

   for (int i = 0; i != len; i++) {
       int position = i << 1;
       int high;
       int low;

       if (chars[position] < 'A') {
           high = chars[position] - 0x30;
       } else if (chars[position] > 'Z') {
           high = chars[position] - 0x57;
       } else {
           high = chars[position] - 0x37;
       }

       if (chars[position + 1] < 'A') {
           low = chars[position + 1] - 0x30;
       } else if (chars[position + 1] > 'Z') {
           low = chars[position + 1] - 0x57;
       } else {
           low = chars[position + 1] - 0x37;
       }

       high = high << 4;

       bytes[i] = (byte) (high + low);
   }

   return bytes;
}

第2个回答  2013-07-10
你自己把这个字符串打转化成二进制就可以了。