我在我的网络应用程序中使用 wicket。我将字符串保存在一些 .properties 文件中,如下所示:
foo.properties
page.label=dummy
在 html 文件中,我可以按如下方式访问字符串 page.label
:
index.html
<wicket:message key="page.label">Default label</wicket:message>
现在我为我的应用程序编写了一些 junit 测试用例,并且想要访问保存在属性文件中的字符串。我的问题是,如何从属性文件中读取字符串?
最佳答案
试试这个
import java.io.FileInputStream;
import java.util.Properties;
public class MainClass {
public static void main(String args[]) throws IOException {
Properties p = new Properties();
p.load(new FileInputStream("foo.properties"));
Object label = p.get("page.label");
System.out.println(label);
}
}
此部分允许您从任意位置读取所有属性文件并将它们加载到属性中
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class MainClass {
private static String PROPERTIES_FILES_PATHNAME = "file:///Users/ftam/Downloads/test/";// for mac
public static void main(String args[]) throws Exception {
Properties p = new Properties();
List<File> files = getFiles();
for(File file : files) {
FileInputStream input = new FileInputStream(file);
p.load(input);
}
String label = (String) p.get("page.label");
System.out.println(label);
}
private static List<File> getFiles() throws IOException, URISyntaxException {
List<File> filesList = new ArrayList<File>();
URL[] url = { new URL(PROPERTIES_FILES_PATHNAME) };
URLClassLoader loader = new URLClassLoader(url);
URL[] urls = loader.getURLs();
File fileMetaInf = new File(urls[0].toURI());
File[] files = fileMetaInf.listFiles();
for(File file : files) {
if(!file.isDirectory() && file.getName().endsWith(".properties")) {
filesList.add(file);
}
}
return filesList;
}
}
关于java - 如何从 junit-tests 中的 .properties 文件读取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13699153/