1、将二进制文件变成字节
public static byte[] getFile(String path) throws Exception {
byte[] b = null;
File file = new File(path);
FileInputStream fis = null;
ByteArrayOutputStream ops = null;
try {
if (!file.exists()) {
System.out.println("文件不存在!");
}
if (file.isDirectory()) {
System.out.println("不能上传目录!");
}
byte[] temp = new byte[2048];
fis = new FileInputStream(file);
ops = new ByteArrayOutputStream(2048);
int n;
while ((n = fis.read(temp)) != -1) {
ops.write(temp, 0, n);
}
b = ops.toByteArray();
} catch (Exception e) {
throw new Exception();
} finally {
if (ops != null) {
ops.close();
}
if (fis != null) {
fis.close();
}
}
return b;
}
2、将字节保存成文件,如果文件存在,会被覆盖,要自己判断
public static void saveFile(byte[] b, String path)
throws Exception {
File file = new File(path);
FileOutputStream fis = null;
BufferedOutputStream bos = null;
try {
fis = new FileOutputStream(file);
bos = new BufferedOutputStream(fis);
bos.write(b);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (bos != null) {
bos.close();
}
if (fis != null) {
fis.close();
}
}
}
3、直接打开文件:先调用saveFile, 将文件保存到一个临时目录,调用了cmd命令打开文件,windows操作系统自动调用应用程序打开,非Windows系统上无效。
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd /c start " + path);