2

我在我的网络应用程序中使用检票口。我将字符串保存在一些 .properties 文件中,如下所示:

foo.properties

page.label=dummy

page.label在 html 文件中,我可以按如下方式访问字符串:

索引.html

<wicket:message key="page.label">Default label</wicket:message>

现在我为我的应用程序编写了一些 junit 测试用例,并想访问保存在属性文件中的字符串。我的问题是,如何从属性文件中读取字符串?

4

5 回答 5

4

尝试这个

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;
    }
}
于 2012-12-04T09:06:58.360 回答
2

考虑到组件树,Wicket 有自己的本地化资源方式。请参阅StringResourceLoader 的 javadoc

加载资源的一种方法是:

WicketTester tester = new WicketTester(new MyApplication());
tester.startPage(MyPage.class);
Localizer localizer = tester.getApplication().getResourceSettings()
                            .getLocalizer();
String foo = localizer.getString("page.label",tester.getLastRenderedPage(), "")
于 2012-12-04T16:33:24.933 回答
1

使用Apache Commons Configuration是一个不错的选择!

于 2012-12-04T09:00:04.697 回答
1

你可以使用load然后get("page.label")

于 2012-12-04T09:02:02.720 回答
0

在你的班级中有这个字段:

import java.util.ResourceBundle;

private static ResourceBundle settings = ResourceBundle.getBundle("test",Locale.getDefault());

然后是test.properties这样的文件:

com.some.name=someValueHere

最后,您可以通过这种方式访问​​属性值:

private String fieldName = settings.getString("com.some.name");
于 2013-12-24T10:50:16.177 回答