Dor*_*nai 14 java file-io classpath
如何保存/加载位于我的课程所在的文件?我之前没有到该位置的物理路径,我想动态地找到该文件.
谢谢
编辑:
我想加载一个XML文件并写入和读取它,我不知道如何解决它.
Bal*_*usC 38
使用ClassLoader#getResource()或getResourceAsStream()获得他们作为URL或InputStream从classpath.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/file.ext");
// ...
Run Code Online (Sandbox Code Playgroud)
或者,如果它与当前类位于同一个包中,您也可以按如下方式获取它:
InputStream input = getClass().getResourceAsStream("file.ext");
// ...
Run Code Online (Sandbox Code Playgroud)
拯救是一个独特的故事.如果文件位于JAR文件中,则无效.如果可以确保文件已展开且可写,则将URLfrom 转换getResource()为File.
URL url = classLoader.getResource("com/example/file.ext");
File file = new File(url.toURI().getPath());
// ...
Run Code Online (Sandbox Code Playgroud)
然后你可以FileOutputStream用它构造一个.
Pet*_*rey 12
如果您的类是从文件系统加载的,则可以尝试以下操作.
String basePathOfClass = getClass()
.getProtectionDomain().getCodeSource().getLocation().getFile();
Run Code Online (Sandbox Code Playgroud)
要获取该路径中的文件,您可以使用
File file = new File(basePathOfClass, "filename.ext");
Run Code Online (Sandbox Code Playgroud)
new File(".").getAbsolutePath() + "relative/path/to/your/files";
在一般情况下你不能.从类加载器加载的资源可以是任何内容:目录中的文件,嵌入在jar文件中的文件,甚至可以通过网络下载.
这是对彼得回应的扩展:
如果您希望该文件与当前类位于同一类路径中(例如:project/classes):
URI uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
File file = new File(new File(uri), PROPERTIES_FILE);
FileOutputStream out = new FileOutputStream(createPropertiesFile(PROPERTIES_FILE));
prop.store(out, null);
Run Code Online (Sandbox Code Playgroud)
如果您希望文件位于不同的类路径中(例如:progect/test-classes),只需替换this.getClass()为TestClass.class.
Properties prop = new Properties();
System.out.println("Resource: " + getClass().getClassLoader().getResource(PROPERTIES_FILE));
InputStream in = getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
if (in != null) {
try {
prop.load(in);
} finally {
in.close();
}
}
Run Code Online (Sandbox Code Playgroud)
Properties prop = new Properties();
prop.setProperty("Prop1", "a");
prop.setProperty("Prop2", "3");
prop.setProperty("Prop3", String.valueOf(false));
FileOutputStream out = null;
try {
System.out.println("Resource: " + createPropertiesFile(PROPERTIES_FILE));
out = new FileOutputStream(createPropertiesFile(PROPERTIES_FILE));
prop.store(out, null);
} finally {
if (out != null) out.close();
}
Run Code Online (Sandbox Code Playgroud)
private File createPropertiesFile(String relativeFilePath) throws URISyntaxException {
return new File(new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()), relativeFilePath);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44252 次 |
| 最近记录: |