Android : How to read file in bytes?
here it's a simple:
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add permission in manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Android | How Read file to byte array?
To read a File
you would be best served with a FileInputStream
.
You create a File
object pointed to your file on the device. You open the FileInputStream
with the File
as a parameter.
You create a buffer of byte[]
. This is where you will read your file in, chunk by chunk.
You read in a chunk at a time with read(buffer)
. This returns -1 when the end of the file has been reached. Within this loop you must do the work on your buffer. In your case, you will want to send it using your protocol.
Do not try to read the entire file at once otherwise you will likely get an OutOfMemoryError
.
File file = new File("input.bin");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte buffer[] = new byte[4096];
int read = 0;
while((read = fis.read(buffer)) != -1) {
// Do what you want with the buffer of bytes here.
// Make sure you only work with bytes 0 - read.
// Sending it with your protocol for example.
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.toString());
} catch (IOException e) {
System.out.println("Exception reading file: " + e.toString());
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ignored) {
}
}
Elegant way to read file into byte[] array in Java
A long time ago:
Call any of these
byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input)
From
http://commons.apache.org/io/
If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library
Today (Java 7+ or Android API Level 26+)
Luckily, we now have a couple of convenience methods in the nio packages. For instance:
byte[] java.nio.file.Files.readAllBytes(Path path)
Javadoc here
Reading a resource sound file into a Byte array
You do have byte array length as you can see:
InputStream inStream = context.getResources().openRawResource(R.raw.cheerapp);
byte[] music = new byte[inStream.available()];
And then you can read whole Stream into byte array easily.
Of course I would recommend that you do check when it comes to the size and use ByteArrayOutputStream with smaller byte[] buffer if needed:
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling function
}
If you'll be doing lots of IO operations I recommend that you make use of org.apache.commons.io.IOUtils. That way you won't need to worry too much about quality of your IO implementation and once you import JAR into your project you would just do:
byte[] payload = IOUtils.toByteArray(context.getResources().openRawResource(R.raw.cheerapp));
Android - How to properly parse a file consisting of bytes delimited with space?
String.getBytes not the same as Bytes.toString. When you convert byte to string you receive number of chars, for example byte value 127 is 3 char ['1','2','7'] with byte codes [49, 50, 55]
byte b = 127;
System.out.println(b + ""); // 127
String "127".getBytes() returns this array [49, 50, 55]
System.out.println(Arrays.toString("127".getBytes())); // [49, 50, 55]
To properly read value you need next code:
byte[] bytes = "127".getBytes();
String value = "";
for (byte part : bytes) {
value += (char)part;
}
System.out.print(value); // 127
If you want to receive byte value you need parse this string via
byte b = Byte.parseByte(value);
Related Topics
How to Parse JSON from a Java Httpresponse
Android Web Scraping with a Headless Browser
How to Get Current Location in Googlemap Using Fusedlocationproviderclient
Android: Textview Automatically Truncate and Replace Last 3 Char of String
How to Hash a String in Android
Change Icons of Checked and Unchecked for Checkbox for Android
Java Lang Unsupportedclassversion Error in Xamarin Studio
How to Execute JavaScript on Android
Android:How to Read File in Bytes
How to Use the Java 8 Stream API on Android API < 24
Android Studio Cannot Resolve Symbol But Code Executes Correctly
How to Change the Text Color in a String to Multiple Colors in Java
Fatal Error: Invalid Layout of Java.Lang.String at Value
How to Use Weakreference in Java and Android Development
How to Avoid Garbage Collection Delays in Java Games? (Best Practices)
How to Set Thousands Separator in Java