* @param 写入文件的路径
* @param 写入文件的文件名
*/
public static void write(byte[] bt, String filePath, String fileName) {
//File file = new File("D:", "mm");
File file = new File(filePath, fileName);
OutputStream oo = null;
try {
oo = new FileOutputStream(file, true);
oo.write(bt);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oo != null) {
try {
oo.flush();
oo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
*
* 获取有符号数的8个bit位
* Aug 11, 2011
* @param b
* @return
*/
public static String getBit(byte b) {
StringBuffer sbf = new StringBuffer();
int[] bit = new int[8];
for (int i = 0; i < bit.length; i++) {
bit[8 - i - 1] = (b >> i) & 1;
}
for (int i : bit) {
sbf.append(i);
}
return sbf.toString();
}
/**
* 将有符号数转换为无符号数
*
* Aug 11, 2011
* @author 吕建明
* @param p 需要转换的字节
* @return
*/
public static int getU1(byte p) {
return p & 0xff;
}
/**
*
*
Discription:[将无符号数转换为有符号数]
* @param intValue
* @return
* @author:[创建者中文名字]
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public static int getIntA(int intValue) {
int byteva lue;
int temp = intValue % 256;
if (intValue < 0) {
byteva lue = temp < -128 256 + temp : temp;
} else {
byteva lue = temp > 127 temp - 256 : temp;
}
return byteva lue;
}
/**
*
*
Discription:[获取文件的字节流]
* @param filePath 文件的路径
* @param fileName 文件名称
* @return 文件被容转换成的字节数组
* @author:[创建者中文名字]
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
private static byte[] getContent(String filePath, String fileName) {
File file = new File(filePath, fileName);
InputStream strm = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] ll = new byte[1024];
strm = new FileInputStream(file);
int len = -1;
while ((len = strm.read(ll)) != -1) {
baos.write(ll, 0, len);
}
} catch (Exception e1) {
e1.printStackTrace();
}
return baos.toByteArray();
}
}
测试主函数:
public class TestMain {
/**
*
* Aug 11, 2011
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
byte a = -1;
// 获取有符号位的8个bit位
System.out.println(TestTool.getBit(a));
// 将有符号数转换为无符号数(正整数还是自己本身)
System.out.println(TestTool.getU1(a));
// 将无符号数转换为有符号数(0-255)
System.out.println(TestTool.getIntA(255));
byte[] bt = new byte[]{-1};
//往文件里写byte数组
TestTool.write(bt, "D:", "11");
// 读取指定文件转成字节数组
byte[] bread = TestTool.read("D:", "mm");
for(int i = 0; i< bread.length; i++){
System.out.pr