This is my code to create a file.
public void writeToFile(byte[] array)
{
try
{
String path = "/data/data/lalallalaa.txt";
FileOutputStream stream = new FileOutputStream(path);
stream.write(array);
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
When I try to send my file to my server by just calling the path String path = "/data/data/lalallalaa.txt";
I get this logcat error message:
03-26 18:59:37.205: W/System.err(325): java.io.FileNotFoundException: /data/data/lalallalaa.txt
I don't understand why it can't find a file that is "supposedly" created already.
Java – How to save byte[] to a file write is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths. get("/path/file"); Files. write(path, bytes);
write(bytes, new File(path)); With Apache Commons: FileUtils. writeByteArrayToFile(new File(path), bytes);
Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later. The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
But...if you have a byte array and that is all, it doesn't have a filename - those are only available within the operating system file system for actual files, and a byte array does not have any file associated with it, even if it was read from or has been written to a file.
I think you'd better add close function of FileOutputStream for clear code
It works me perfectly
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With