写入文件时如何使用短路径
How to use short path when writing a file
当我在我的代码中得到一些东西时,我使用像
这样的短路径
this.getStylesheets().add("/css/editorTool.css");
但是当我写一个新文件时,我给出了确切的路径——比如:
File f = new File("D:\IdeaProjects\SmartCRM for TB\EditorTool\resourses\html\test.html");
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(html);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
因为我必须在一些用户中分发这个应用程序,所以我无法保证我的应用程序的绝对路径是相同的。我怎样才能把它写成“path_to_the_folder_that_is_contained_in_app + 文件名?
可以使用系统属性 "user.dir"获取当前工作路径,代码如下:
String currentWorkingPath = System.getProperty("user.dir");
String fullPath = currentWorkingPath + File.separator+ fileName;
那么当程序 运行 在任何 PC 上时,文件将在 currentWorkingPath 下。
您可以使用java.lang.Class<T>
的getResource()
方法
The java.lang.Class.getResource() finds a resource with a given name
用法:
File file = new File(getClass().getResource("html/test.html").getPath());
当我在我的代码中得到一些东西时,我使用像
这样的短路径this.getStylesheets().add("/css/editorTool.css");
但是当我写一个新文件时,我给出了确切的路径——比如:
File f = new File("D:\IdeaProjects\SmartCRM for TB\EditorTool\resourses\html\test.html");
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(html);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
因为我必须在一些用户中分发这个应用程序,所以我无法保证我的应用程序的绝对路径是相同的。我怎样才能把它写成“path_to_the_folder_that_is_contained_in_app + 文件名?
可以使用系统属性 "user.dir"获取当前工作路径,代码如下:
String currentWorkingPath = System.getProperty("user.dir");
String fullPath = currentWorkingPath + File.separator+ fileName;
那么当程序 运行 在任何 PC 上时,文件将在 currentWorkingPath 下。
您可以使用java.lang.Class<T>
getResource()
方法
The java.lang.Class.getResource() finds a resource with a given name
用法:
File file = new File(getClass().getResource("html/test.html").getPath());