A method created to store PDF files and CSV files in the BLOB type of Oracle. Until now, I have rarely dealt with byte arrays, so I will write it down so that I will not forget it in the future.
public byte[] convertFile(File file) {
try (FileInputStream inputStream = new FileInputStream(file);) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while(true) {
int len = inputStream.read(buffer);
if(len < 0) {
break;
}
bout.write(buffer, 0, len);
}
return bout.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
}
Based on what you told me in the comments, I will write some modified methods.
A version that fixes the point that the infinite loop by while is not cool and forgetting to close ByteArrayoutputStream. The method described later is simpler, so if you have Java 7 or above, you should use method ② or later.
public byte[] convertFile(File file) {
File file = new File(dir + name);
try (FileInputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream bout = new ByteArrayOutputStream();) {
byte[] buffer = new byte[1024];
int len = 0;
while((len = inputStream.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
return bout.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
How to use apache.commons.compress.utils.IOUtils.toByteArray. Any environment where you can add a library is OK.
public byte[] convertFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
return IOUtils.toByteArray(inputStream);
}
How to use java.nio.file.Files.readAllBytes (). Note that it can only be used with Java 7 or above.
public byte[] convertFile(File file) throws IOException {
return Files.readAllBytes(file.toPath());
}
How to use java.io.InputStream.transferTo (). Note that it can only be used with Java 9 or above.
public byte[] convertFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
return inputStream.transferTo(outputStream);
}
--This time it's Java 8, so using java.nio.file.Files.readAllBytes () may be the simplest with the fewest lines. --Failed to run into the method of using OutputStream and InputStream. I should have investigated more before implementing it ...
Recommended Posts