java.io.IOException:在文件中创建和写入时文件路径无效

问题描述 投票:0回答:2

我试图在目录中创建一个文件但是当代码执行时它会带回错误'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进一步发送给客户。

java file java-io ioexception
2个回答
0
投票

我找到了问题的解决方案。解决方案是在文件名字符串中添加'.trim()'。当文件进来时,一定有一些空白区域。


-1
投票

我尝试通过将返回类型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");
}
© www.soinside.com 2019 - 2024. All rights reserved.