题目:
接受一个参数,参数表示本地一个文件的地址,
需要读取此地址的文件,并且通过16进制格式输出(每行有16个字符,并且每个字符中间有一个空格)
------解决方案--------------------
睡前大致写了下,后面的格式化处理自己写下吧,今天累死了,睡觉去了
public static void outputFileWitHex(String path){
byte[] buffer = null;
FileInputStream fis = null;
int n;
String ret = "";
File file = new File(path);
try {
fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
for (int i = 0; i < buffer.length; i++) {
String hex = Integer.toHexString(buffer[i] & 0xFF);
if (hex.length() == 1) {
hex = "0x" + hex;
}
ret += hex.toUpperCase();
}
System.out.println(ret);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
------解决方案--------------------
简单修改了下上述代码,功能已经可以实现,
public static void outputFileWitHex(String path){
byte[] buffer = null;
FileInputStream fis = null;
int n;
String ret = "";
File file = new File(path);
try {
fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
String lineSeparator = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
for (int i = 0; i < buffer.length; i++) {
String hex = Integer.toHexString(buffer[i] & 0xFF)+" ";//每个字符后面添加空格.
if(i==15)
{
//hex+=lineSeparator;//兼容所有系统