保存文件时空指针异常 Java

Nullpointer exception when saving file Java

您好,我在将图像文件写入 Tomcat 中的地图时遇到了一些问题。

在 JSP 页面中,我有以下代码:

<div class="patterninfo">
        <!-- file upload -->
        <input type="file" name="file" />
        <!-- einde fileupload -->
        <input type="submit" name="button" value="Add new pattern" class="button">
</div>

在 EditorServlet 中,我将这部分代码写入 tomcat 映射 (tomcat 8-0-18)。

Part FilePart = req.getPart("file");
InputStream imageInputStream = FilePart.getInputStream();
String FileName = FilePart.getSubmittedFileName();

int i = imageInputStream.available();
byte[]b = new byte[i];
imageInputStream.read(b);

FileOutputStream fos = new FileOutputStream("\webapps\Ass2\images\"+FileName);
fos.write(b);
imageInputStream.close();

异常(系统找不到给定的路径)

希望大家能帮帮我。我需要将图像文件保存到 \webapp\Ass2\images\ 文件夹中。

非常感谢。

错误信息不言自明,路径\webapp\Ass2\images\不存在,您需要先创建它,然后再将文件放入其中。

String file="\webapps\Ass2\images\"+FileName;
File f = new File(file);
f.getParentFile().mkdirs(); 
f.createNewFile();

FileOutputStream fos = new FileOutputStream(file);
fos.write(b);
imageInputStream.close();