我试图在目录中创建一个文件但是当代码执行时它会带回错误'java.io.IOException: Invalid file path'
。代码确实创建了名为“ServerUploads”的目录,但它没有创建该文件。以下是代码段:
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;
}
作为参数传递的文件名是'upload.txt'。我不确定为什么它不起作用。任何帮助表示赞赏。谢谢!。请参阅我需要return
String
而不是void
的方法,因为我必须将return
进一步发送给客户。
我找到了问题的解决方案。解决方案是在文件名字符串中添加'.trim()'。当文件进来时,一定有一些空白区域。
我尝试通过将返回类型String
更改为void
来跟踪代码块,因为没有返回任何内容。有效。文件夹和文件都已创建。这是相同的代码块:
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();
}
从main调用以上函数:
public static void main(String args[]) throws IOException {
performUploadOperation("abc".getBytes(),"testfile");
}