[英]How to get Java web application path?
I have a fileupload servlet in java. 我在Java中有一个fileupload servlet。 And i want to set path to upload folder, to it waork on any server.
而且我想设置上传文件夹的路径,在任何服务器上都无法访问。 I say:
我说:
File disk = new File("/myportlet/upload/"+item.getName());
item.write(disk);
But nothing saved. 但是什么都没有保存。 When i use absolute path to upload folder all work fine.
当我使用绝对路径上传文件夹时,一切正常。
So how to set path to upload folder in server? 那么如何设置服务器上载文件夹的路径呢?
The leading "/" at the new File()
constructor refers to the root of the file system. new File()
构造函数中的前导“ /”是指文件系统的根。 The file will be written into a directory named /myportlet/upload
, in your code. 该文件将在您的代码中写入名为
/myportlet/upload
的目录。
As the comments implied, writing into appserver-internal directories violates the spec and is generally a terrible idea - I honestly can't think of one proper use for doing so. 正如评论所暗示的那样,写入appserver-internal目录违反了规范,并且通常是一个糟糕的主意-老实说,我想不出这样做的正确用法。 What you want to do is to read the target path from a parameter - for example, a servlet's initialization parameter or a context initialization parameter - and use that.
您要做的是从参数(例如,Servlet的初始化参数或上下文初始化参数)中读取目标路径,然后使用该路径。
I used the below snippet. 我使用了以下代码段。 It worked fine in windows server.
它在Windows Server中工作正常。
File f=new File("sample.xls");
f.createNewFile();
FileOutputStream fos=null;
if(f != null){
fos=new FileOutputStream(f);
fos.write(b);
fos.flush();
fos.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.