我该如何保存/加载一个位于我的类所在位置的文件?我不知道那个位置的物理路径,我想要动态地查找该文件。
我想要加载一个XML文件并对其进行读写操作,但不确定如何访问它。
我想要加载一个XML文件并对其进行读写操作,但不确定如何访问它。
使用ClassLoader#getResource()
或getResourceAsStream()
从类路径获取它们作为URL
或InputStream
。
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/file.ext");
// ...
如果它与当前类在同一个包中,也可以按以下方式获取:
InputStream input = getClass().getResourceAsStream("file.ext");
// ...
保存文件是另外一回事。如果文件位于JAR文件中,则此方法无法工作。如果您可以确保文件已扩展并且可以写入,则可以将getResource()
返回的URL
转换为File
。
URL url = classLoader.getResource("com/example/file.ext");
File file = new File(url.toURI().getPath());
// ...
然后您可以使用它构造一个FileOutputStream
。
url.toURI()
дјҡеҜјиҮҙNullPointerException
гҖӮ - naXa stands with Ukraineurl
是否为 null
。对于任何你试图使用点号运算符 .
访问的其他 Java 变量来说,情况都是一样的。每个自重的 Java 开发者都知道这一点。 - BalusCgetResource
返回null,它不允许你创建一个文件。 - ScrappyDevURISyntaxException
。 - another假设你的类从文件系统加载,那么你可以尝试以下操作。
String basePathOfClass = getClass()
.getProtectionDomain().getCodeSource().getLocation().getFile();
要获取该路径下的文件,您可以使用以下方法
File file = new File(basePathOfClass, "filename.ext");
File file = new File(basePathOfClass + "Filename.txt");
- anothernew File(".").getAbsolutePath() + "relative/path/to/your/files";
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);
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();
}
}
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();
}
private File createPropertiesFile(String relativeFilePath) throws URISyntaxException {
return new File(new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()), relativeFilePath);
}