【发布时间】:2019-08-07 10:03:34
【问题描述】:
我正在尝试在目录中创建一个文件,但是当代码执行时,它会返回错误 'java.io.IOException: Invalid file path'。
并且代码确实创建了名为“ServerUploads”的目录,但它不会创建文件。
下面是一个代码 sn-p :
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 发送给客户。
【问题讨论】:
-
您好,您可以尝试在文件构造函数中切换
\` to/` 吗?还有,字节数组是干什么用的? -
我已经用完整的方法更新了我的代码,不幸的是正斜杠不起作用。
-
@GavinEverett 您的代码与
return sucess;不同,它应该是String sucess =....或直接return "600 - The file has been successfully uploaded!"。您可以从控制台添加完整的异常以及您如何调用performUploadOperation(..,...) -
这里的
createNewFile()调用是浪费时间和空间,exists()调用也是如此。
标签: java file java-io ioexception