File to byte[] in Java
It depends on what best means for you. Productivity wise, don't reinvent the wheel and use Apache Commons. Which is here FileUtils.readFileToByteArray(File input)
.
byte[] to file in Java
Use Apache Commons IO
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Or, if you insist on making work for yourself...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
Converting a 3GB file into a byte array
Use InputStream
and OutputStream
.
They are meant for big amounts of data, for example, when you work with 3GB of data and can't load it into memory.
If you are trying to upload a file, use FileInputStream
. Create a File
object, pass it to the FileOutputStream
constructor and start reading bytes from its InputStream
to a byte[]
buffer and send the bytes with an OutputStream
to the server.
This approach will not cause an OutOfMemoryError
,because you are reading only enough bytes to fill up the buffer, which should be about 2KB - 8KB in size. After the buffer is full, you write the bytes to the server. After the buffer was written to the server, you read into the buffer again, and the process keeps going on until the whole file is uploaded.
Example using FileInputStream
File file = new File("yourfile.txt");
FileInputStream fis = null;
OutputStream outputStream = null;
url = new URL(desiredUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
fis = new FileInputStream(file);
connection.setDoOutput(true);
outputStream = connection.getOutputStream();
int actuallyRead;
byte[] buffer = new byte[2048];
while ((actuallyRead = fis.read(buffer)) != -1) {
//do something with bytes, for example, write to the server
outputStream.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Note: This approach does not mean you need to reconnect to the server
each time a buffer is filled. It will continuously write to the
server, until it is done processing the file. This will happen all
under the same, single connection.
Convert file to byte array and vice versa
I think you misunderstood what the java.io.File
class really represents. It is just a representation of the file on your system, i.e. its name, its path etc.
Did you even look at the Javadoc for the java.io.File
class? Have a look here
If you check the fields it has or the methods or constructor arguments, you immediately get the hint that all it is, is a representation of the URL/path.
Oracle provides quite an extensive tutorial in their Java File I/O tutorial, with the latest NIO.2 functionality too.
With NIO.2 you can read it in one line using java.nio.file.Files.readAllBytes().
Similarly you can use java.nio.file.Files.write() to write all bytes in your byte array.
UPDATE
Since the question is tagged Android, the more conventional way is to wrap the FileInputStream
in a BufferedInputStream
and then wrap that in a ByteArrayInputStream
.
That will allow you to read the contents in a byte[]
. Similarly the counterparts to them exist for the OutputStream
.
Convert file to byte array then to string then to byte array then to the original file
I found an answer one has to use JAVA 8 java.util.Base64 to encode and decode the bytes without loosing information on the document. I hope it will be of help to someone.
/*
* 1. How to convert an image file to byte array?
*/
try {
File file = new File("C:/Users/qwerty/Downloads/factura.pdf");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//create FileInputStream which obtains input bytes from a file in a file system
//FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
//Writes to this byte array output stream
bos.write(buf, 0, readNum);
// System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
bos.close(); // should be inside a finally block
//We have the bytes now convert to String
// ENCODING
String encodedDoc= Base64.getEncoder().encodeToString(bytes);
System.out.println(encodedDoc);
// DECODING
int size = bytes.length;
InputStream isfilecontent = null;
//byte[] b = new byte[size];
isfilecontent = new ByteArrayInputStream(Base64.getDecoder().decode(encodedDoc));
//writing the downloaded data into a PDF file
FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/qwerty/Downloads/myfactura.pdf");
/* use binary I/O to prevent line based operation messing with the encoding.*/
byte[] buf2 = new byte[2048];
int b_read = 0;
while ( (b_read = isfilecontent.read(buf2)) > 0) {
fileOutputpdf.write(buf2, 0, b_read);
}
fileOutputpdf.flush();
//closed the output stream
fileOutputpdf.close();
} catch (IOException e) {
// handle IOException
System.out.println(e.getMessage());
}
Converting file to byte array slowing down the app
Doing I/O on the main application thread will freeze your UI for the duration of that I/O, meaning that your UI will be unresponsive. Moving I/O to a background thread is necessary for a well-behaved UI.
Android's insistence that we can only safely update the UI from the main application thread means that you need to use an AsyncTask
, a Thread
and stuff like runOnUiThread()
, RxJava/RxAndroid, or other approaches to arrange both the background work and updating the UI when that background work is done.
In your case, doing the convert()
logic on a background thread, and updating the waveView
on the main application thread, should help.
Read bytes from file Java
As of Java 7, reading the whole of a file really easy - just use Files.readAllBytes(path)
. For example:
Path path = Paths.get("my_file.txt");
byte[] data = Files.readAllBytes(path);
If you need to do this more manually, you should use a FileInputStream
- your code so far allocates an array, but doesn't read anything from the file.
To read just a portion of a file, you should look at using RandomAccessFile
, which allows you to seek to wherever you want. Be aware that the read(byte[])
method does not guarantee to read all the requested data in one go, however. You should loop until either you've read everything you need, or use readFully
instead. For example:
public static byte[] readPortion(File file, int offset, int length)
throws IOException {
byte[] data = new byte[length];
try (RandomAccessFile raf = new RandomAccessFile(file)) {
raf.seek(offset);
raf.readFully(data);
}
return data;
}
EDIT: Your update talks about seeing text such as [B@6e0b..
. That suggests you're calling toString()
on a byte[]
at some point. Don't do that. Instead, you should use new String(data, StandardCharsets.UTF_8)
or something similar - picking the appropriate encoding, of course.
Related Topics
Compare Two Objects With .Equals() and == Operator
Java: Convert List≪String≫ to a Join()D String
How to Format the Day of the Month to Say "11Th", "21St" or "23Rd" (Ordinal Indicator)
Java Hashmap: How to Get Key from Value
Org.Xml.Sax.Saxparseexception: Content Is Not Allowed in Prolog
How to Generate Exceptions from Repaintmanager
Modify a Class Definition'S Annotation String Parameter At Runtime
Including Jars in Classpath on Commandline (Javac or Apt)
Causes of Getting a Java.Lang.Verifyerror
Jtextfields on Top of Active Drawing on Jpanel, Threading Problems
Java Reflection: How to Get the Name of a Variable
How to Pretty Print Xml from Java
Something Seems Wrong With the Layout, Jbutton Showing Unexpected Behaviour At Resize of the Window