java二进制文件与字节之间的转化

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值