I have a byte array, i want to create an image file(bmp file) of byte array. I create an images folder in src (my path is src/images/test.bmp). my code is in below, in
OutputStream stream = new FileOutputStream(file);
i get error. what is my problem? How can i solve this?
public static void saveImage() {
String s="........................";
byte[] dataCustImg = Base64.decode(s.getBytes());
File file = new File("/images/test.bmp");
if (file.exists()) {
file.delete();
}
file = new File("/images/test.bmp");
file.mkdirs();
try {
OutputStream stream = new FileOutputStream(file);
stream.write(dataCustImg);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Error:
java.io.FileNotFoundException: \images\test.bmp (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
File file = new File("/images/test.bmp");
OK.
if (file.exists()) {
file.delete();
}
Redundant. Remove. new FileOutputStream()
will create a new file.
file = new File("/images/test.bmp");
Redundant. Remove. It already is a File
with this name.
file.mkdirs();
The problem is here. Change to
file.getParentFile().mkdirs();
You are creating a directory called "/images/test.bmp"
, rather than just ensuring that "/images"
exists. This will cause new FileOutputStream()
to fail with an access permission, as you can't overwrite a directory with a file.
try {
OutputStream stream = new FileOutputStream(file);
Now carry on. Note that you will first have to delete the directory "/images/test.bmp"
, manually.