[英]How can I create a file with FileWriter within my project file using relative path
I am using NetBean and glassFish for developing jsp website and its server. 我正在使用NetBean和glassFish开发jsp网站及其服务器。 In the server side, I have a java class which generate a text file using FileWriter:
在服务器端,我有一个Java类,该类使用FileWriter生成文本文件:
FileWriter writer = new FileWriter("the-file-name.txt", true);
But I found that this file was saved in the directory of glassfish: 但是我发现此文件保存在glassfish的目录中:
C:\\Program Files (x86)\\glassfish-4.0\\glassfish\\domains\\domain1\\config
C:\\ Program Files(x86)\\ glassfish-4.0 \\ glassfish \\ domains \\ domain1 \\ config
Also, by checking the path by the code: 另外,通过代码检查路径:
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
the result is also the same with the above path. 结果也与上述路径相同。
How can I get the correct relative path, whether the path of the project or the path of this java file? 如何获得正确的相对路径,无论是项目路径还是此java文件的路径?
This gets the location of the class/jar you are running: 这将获取您正在运行的类/ jar的位置:
String path = System.getProperty("user.dir");
The string path holds the absolute directory, and using somthing like 字符串路径包含绝对目录,并使用类似
path = path.replace("jars", "");
, you can find the root directory for the application. ,您可以找到该应用程序的根目录。 For example, if the jar is in the directory
C:\\Program Files\\Example\\jars
, this would set path to 例如,如果jar位于目录
C:\\Program Files\\Example\\jars
,则将路径设置为
C:\\Program Files\\Example\\
In Servlet 在Servlet中
String filePath = getServletContext().getRealPath("/").replace("\\", "/");
In JSP 在JSP中
String filePath = session.getServletContext().getRealPath("/").replace("\\", "/");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.