Reputation: 31
I am trying to create a file inside a directory but when the code executes it brings back the error 'java.io.IOException: Invalid file path'
.
And the code does create the directory called 'ServerUploads' but it does not create the file.
Below is a code snippet :
public static String performUploadOperation(byte[] file, String filename)
throws IOException {
//creating a directory to store file.
//creating a directory to store users
File userDirectory = new File("C:\\ServerUploads");
//check if directory does not exist.
if (!userDirectory.exists()) {
userDirectory.mkdir();
}
File crreate = new File(userDirectory + "\\" + filename);
if(!crreate.exists())
crreate.createNewFile();
try{
//convert the bytearray retrieved to a file and upload to server folder.
FileOutputStream fos = new FileOutputStream(crreate);
System.out.println(fos.toString());
//write file to directory.
fos.write(file);
fos.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
sucess = "600 - The file has been successfully uploaded!";
return sucess;
}
The filename being passed as argument is 'upload.txt' . I am not sure why it is not working. Any help is appreciated. Thanks!.
Please see I need the method to return
a String
not a void
as I have to further return
it to the client.
Upvotes: 0
Views: 6888
Reputation: 31
I have found the solution to the problem. The solution was to add '.trim()' to the filename string. There must have been some white-space when the file came in.
Upvotes: 2
Reputation: 1088
I tried following code block by just changing return type String
to void
as nothing was returned. It worked. The folder & file both get created.
Here is the code block for same:
public static void performUploadOperation(byte[] file, String filename)
throws IOException {
//creating a directory to store file.
//creating a directory to store users
File userDirectory = new File("C:\\ServerUploads");
//check if directory does not exist.
if (!userDirectory.exists()) {
userDirectory.mkdir();
}
File crreate = new File(userDirectory + "\\" + filename);
if (!crreate.exists())
crreate.createNewFile();
}
Calling above function from main:
public static void main(String args[]) throws IOException {
performUploadOperation("abc".getBytes(),"testfile");
}
Upvotes: -1