Linux和Windows上java中的文件分隔符

Har*_*sha 3 java path filepath

我有一个java swing数据库应用程序需要在Windows和Linux上运行,我的数据库连接细节存储在XML文件中,我加载它们,

这个应用程序可以在Linux上正确加载这个属性,但它不能在Windows上工作,请告诉我如何在多个平台上正确加载文件.

这是代码,

PropertyHandler propertyWriter = new PropertyHandler();

List keys = new ArrayList();
keys.add("ip");
keys.add("database");
Map localProps = propertyWriter.read(keys, "conf" + File.separatorChar + "properties.xml", true);//if false load from the local properties

//get properties from the xml in the internal package
List seKeys = new ArrayList();
seKeys.add("driver");
seKeys.add("username");
seKeys.add("password");

Map seProps = propertyWriter.read(seKeys, "conf" + File.separatorChar + "properties.xml", true);

String dsn = "jdbc:mysql://" + (String) localProps.get("ip") + ":3306/" + (String) localProps.get("database");
jDBCConnectionPool = new JDBCConnectionPool((String) seProps.get("driver"), dsn, (String) seProps.get("username"), (String) seProps.get("password"));
Run Code Online (Sandbox Code Playgroud)

文件阅读器方法,

public Map read(List properties, String path, boolean isConfFromClassPath)
{
    Properties prop = new Properties();
    Map props = new HashMap();
    try {

        if (isConfFromClassPath) {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
            prop.loadFromXML(in);

            for (Iterator i = properties.iterator(); i.hasNext();) {
                String key = (String) i.next();
                props.put(key, prop.getProperty(key));
            }
            in.close();

        } else {
            FileInputStream in = new FileInputStream(path);
            prop.loadFromXML(in);

            for (Iterator i = properties.iterator(); i.hasNext();) {
                String key = (String) i.next();
                props.put(key, prop.getProperty(key));
            }
            in.close();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return props;
}
Run Code Online (Sandbox Code Playgroud)

yia*_*nis 5

如果文件位于jar文件中并由类路径访问,则应始终使用/.

ClassLoader.getResource说"资源的名称是'/' - 标识资源的分隔路径名" 的JavaDocs .

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)