我正在使用球衣来建造休息服务,这将上传一个文件。但我在将文件写入所需位置时遇到问题。 Java抛出一个系统找不到指定的路径错误。这是我的Web服务:
@POST
@Path("/fileupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file")InputStream fileUploadStream, @FormDataParam("file")FormDataContentDisposition fileDetails) throws IOException{
StringBuilder uploadFileLocation= new StringBuilder();
uploadFileLocation.append("c:/logparser/webfrontend/uploads");
uploadFileLocation.append("/"+dateFormat.format(Calendar.getInstance().getTime()));
uploadFileLocation.append("/"+fileDetails.getFileName());
writeToFile(fileUploadStream, uploadFileLocation.toString());
return Response.status(200).entity("File saved to " + uploadFileLocation).build();
}
private void writeToFile(InputStream uploadInputStream, String uploadFileLocation)
{
log.debug("UploadService , writeToFile method , start ()");
try{
int read = 0;
byte[] bytes = new byte[uploadInputStream.available()];
log.info("UploadService, writeToFile method , copying uploaded files.");
OutputStream out = new FileOutputStream(new File(uploadFileLocation));
while ((read = uploadInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
catch(Exception e)
{
log.error("UploadService, writeToFile method, error in writing to file "+e.getMessage());
}
}
答案 0 :(得分:0)
从查看代码(包含异常和堆栈跟踪通常很有帮助),您尝试根据尚不存在的时间戳写入目录。尝试添加对File.mkdir / mkdirs的调用。看到这个问题/答案:FileNotFoundException (The system cannot find the path specified)
旁注 - 除非你有理由不这样做,否则我会考虑使用像Apache commons-io(FileUtils.copyInputStreamToFile)这样的东西进行写作。