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

时间:2019-03-16 13:56:48

标签: java file java-io ioexception

我正在尝试在目录内创建文件,但是当代码执行时,它会带回错误export default { // Configure polyfills: polyfill: { features: [ /* Feature without detect: Note: This is not recommended for most polyfills because the polyfill will always be loaded, parsed and executed. */ { require: 'url-polyfill' // NPM package or require path of file }, /* Feature with detect: Detection is better because the polyfill will not be loaded, parsed and executed if it's not necessary. */ { require: 'intersection-observer', detect: () => 'IntersectionObserver' in window, }, /* Feature with detect & install: Some polyfills require a installation step Hence you could supply a install function which accepts the require result */ { require: 'smoothscroll-polyfill', // Detection found in source: https://github.com/iamdustan/smoothscroll/blob/master/src/smoothscroll.js detect: () => 'scrollBehavior' in document.documentElement.style && window.__forceSmoothScrollPolyfill__ !== true, // Optional install function called client side after the package is required: install: (smoothscroll) => smoothscroll.polyfill() } ] }, // Add it to the modules section: modules: [ 'nuxt-polyfill', ] } 。 代码确实创建了名为“ ServerUploads”的目录,但它没有创建文件。 下面是一个代码段:

'java.io.IOException: Invalid file path'

作为参数传递的文件名是'upload.txt'。我不确定为什么它不起作用。任何帮助表示赞赏。谢谢!。 请参阅我需要 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; } 而不是return的{​​{1}}方法,因为我必须进一步String将它发送给客户端。

2 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。解决方案是在文件名字符串中添加“ .trim()”。文件进入时一定有空白。

答案 1 :(得分:-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");
}