Currently I am making one folder with help of File class
String homeDir = System.getProperty("user.home"); // this will return C:\Users\username
byte[] b1 = abc.getValue(); // contains byte value
String dependentFile = "logoImageData"; // this is the folder name
File f = new File(homeDir+"/"+ dependentFile); // after this line folder will be created like C:\Users\username\logoImageData
FileOutputStream fout=new FileOutputStream(homeDir+"/"+ abc.getName()); // assume abc.getName is image.jpg
fout.write(b1); // this is writing the byte array data into location C:\Users\username\image.jpg
fout.close();
But I want the location to be C:\Users\username\logoImageData\image.jpg
Can please anyone point out what needs to be done to change the FileOutputStream location. I tried and searched but unable to find out the exact thing.
I tried my best to detailed my problem. If still not clear then let me know I will try in another way.
You have two problems:
1) You're assuming that calling the File
constructor will create a directory if it doesn't exist. That's not the case.
2) You're calling the FileOutputStream
constructor and passing in the home directory, not the directory you want to create the file in.
I'd also advise you to use the File(string, string)
and File(File, String)
constructors to avoid all that string concatenation and hard-coding of directory separators... and use the "try with resources" statement to close the stream at the end... or even better, use Files.write
to do it in one shot. Here's the FileOutputStream
version:
String homeDir = System.getProperty("user.home");
File imageDirectory = new File(homeDir, "logoImageData");
// Create the directory if it doesn't exist.
imageDirectory.mkdir();
// TODO: Check the directory now exists, and *is* a directory...
File imageFile = new File(imageDirectory, abc.getName());
try (OutputStream output = new FileOutputStream(imageFile)) {
output.write(abc.getValue());
}
See more on this question at Stackoverflow