Approach
1: Read entire input
stream to ByteArrayOutputStream.
public
static byte[] getByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream
byteArrayOutputStream = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
try {
while ((nRead =
inputStream.read(data, 0, data.length)) != -1) {
byteArrayOutputStream.write(data,
0, nRead);
}
} catch (IOException e) {
e.printStackTrace();
if (inputStream != null) {
inputStream.close();
}
}
return byteArrayOutputStream.toByteArray();
}
App.java
package com.sample.app; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class App { public static byte[] getByteArray(InputStream inputStream) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; try { while ((nRead = inputStream.read(data, 0, data.length)) != -1) { byteArrayOutputStream.write(data, 0, nRead); } } catch (IOException e) { e.printStackTrace(); if (inputStream != null) { inputStream.close(); } } return byteArrayOutputStream.toByteArray(); } public static void main(String args[]) throws IOException { FileInputStream fis = new FileInputStream(new File("/Users/krishna/Desktop/TODO.txt")); byte[] data = getByteArray(fis); System.out.println(new String(data)); } }
Approach
2: From Java9
onwards, inputstream class provides ‘readAllBytes’ method to get byte array
from input stream.
public
byte[] readAllBytes()
public int
readNBytes(byte[] b, int off, int len)
Approach
3: Using
DataInputStream.
byte[]
bytes = new byte[(int) file.length()];
try
(DataInputStream dataInputStream = new DataInputStream(new
FileInputStream(file));) {
dataInputStream.readFully(bytes);
return bytes;
}
package com.sample.app; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class App { public static byte[] getByteArray(File file) throws IOException { byte[] bytes = new byte[(int) file.length()]; try (DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));) { dataInputStream.readFully(bytes); return bytes; } } public static void main(String args[]) throws IOException { byte[] data = getByteArray(new File("/Users/krishna/Desktop/TODO.txt")); System.out.println(new String(data)); } }
Approach
4: Using ‘readFully’
method of RandomAccessFile.
RandomAccessFile
raf = new RandomAccessFile(file, "r");
byte[]
bytes = new byte[(int) raf.length()];
raf.readFully(bytes);
You may
like
No comments:
Post a Comment