0
我正在测试使用属性(mytest.properties)的库(jar)。他们的方法库(JAR)加载属性是通过做更新/编辑属性文件
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
所以,我想测试是当地产的文件中存在发生什么事,当它不存在。为了测试这个,我需要在JVM启动后编辑属性文件。我试过这样做,不起作用。贝娄是我试图编辑属性文件的代码,但总是返回空字符串。 main_mytest.properties的
内容是:mytest.properties和empty.txt的
a=hello world
b=hello java
内容是空的。
""
我的班级是:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class MyPropertyFiles {
final static String resourcesPath = "./mytestproj/src/main/resources";
public static void main(String [] args) throws IOException {
Path source = Paths.get(resourcesPath + "/main_mytest.properties");
Path destination = Paths.get(resourcesPath + "/mytest.properties");
Path empty = Paths.get(resourcesPath + "/empty.txt");
try
{
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "utf-8");
String theString = writer.toString();
System.out.println("!!!!!!!!!!!!!!!! The String: \n" + theString);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
Files.copy(empty, destination, StandardCopyOption.REPLACE_EXISTING);
}
}
}
你确定'mytest.properties'是可写入你当前的权限吗?尝试在第一个'Files.copy'语句之后放置一个调试点,并查看磁盘上文件的内容。这可能有帮助。 –
文件的内容得到更新。但更新内容不在'classLoader.getResourceAsStream(“mytest.properties”);' –
您正在使用的测试属性文件可能不在您的类路径中,这是'ClassLoader'正在查找使用你给它的名字。检查这个答案︰http://stackoverflow.com/questions/19035407/classloader-getresourceasstream-returns-null –