java 二进制存储的_java-将数字存储为二进制文件

我的文件中有以ASCII码写的数字.例如,“ 9”被存储为两个字节57,即总共8位.

我想通过仅将这些数字存储为二进制值(例如从0-9的数字仅使用4位存储)来优化存储.

有帮助吗?

解决方法:

你可以这样写二进制文件

import java.io.ByteArrayInputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class Bin {

public static void main(String[] args) throws IOException {

FileOutputStream fos = new FileOutputStream("\\test.bin");

String digits="12345";

char[] chars = digits.toCharArray();

for ( int i = 0 ; i < chars.length ; i+= 2 ) {

byte b1 = (byte) (chars[i] - (byte) '0');

byte b2 = (byte) (i < chars.length-1 ? chars[i+1] - (byte) '0' : 0xf);

fos.write((byte) ((b1 << 4) | b2 ));

}

fos.close();

FileInputStream fis = new FileInputStream("\\test.bin");

StringBuffer result = new StringBuffer();

byte[] buf = new byte[100];

int read = fis.read(buf);

ByteArrayInputStream bais = new ByteArrayInputStream(buf);

for ( int i = 0 ; i < read ; i++ ) {

byte both = (byte) bais.read();

byte b1 = (byte) ((both >> 4 ) & 0xf);

byte b2 = (byte) (both & 0xf) ;

result.append( Character.forDigit(b1, 10));

if ( b2 != 0xf ) {

result.append(Character.forDigit(b2,10));

}

}

System.out.println(result.toString());

}

}

但我怀疑这会很有用

标签:store,file,ascii,java

来源: https://codeday.me/bug/20191202/2085408.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值