Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a byte array to a file in Android?

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.

like image 711
EGHDK Avatar asked Mar 26 '12 19:03

EGHDK


People also ask

How do I write a byte array to a file?

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);

How do I create a byte file?

write(bytes, new File(path)); With Apache Commons: FileUtils. writeByteArrayToFile(new File(path), bytes);

Which stream is used to write a byte array to a file?

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.

Can we get file name from byte array Java?

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.


1 Answers

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());
}
like image 195
Trần Thị Diệu My Avatar answered Sep 21 '22 19:09

Trần Thị Diệu My