Java 中如何把文件(file)转化字节数组呢?
方式一:
-
-
-
-
-
-
-
- public static byte[] fileTobytes(final File file) throws IOException {
- byte[] data = null;
- if (file.exists()) {
- FileInputStream fileInputStream = new FileInputStream(file);
- int length = fileInputStream.available();
- data = new byte[length];
- fileInputStream.read(data);
- fileInputStream.close();
- }
- return data;
- }
方式二:
-
-
-
-
-
-
-
- public static byte[] readBytes4file(File file) throws IOException{
- BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
- ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
-
-
-
- byte[] temp = new byte[1024];
- int size = 0;
- while ((size = in.read(temp)) != -1) {
- out.write(temp, 0, size);
- }
- in.close();
-
- byte[] content = out.toByteArray();
- return content;
- }