本文介绍了如何使用Java在多个平台上正确加载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a java swing database application which needs to be run on Windows and Linux. My database connection details are stored in a XML file and I load them.

此应用程序可以在Linux上正确加载此属性,但在Windows上不起作用.

This application can load this properties on Linux properly but it is not working on Windows.

如何使用Java在多个平台上正确加载文件?

How do I load files on multiple platforms properly using Java?

这是代码:

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"));

文件读取器方法:

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;
}

推荐答案

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

If the file is in a jar file and accessed by the classpath then you should always use /.

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

The JavaDocs for the ClassLoader.getResource say that "The name of a resource is a '/'-separated path name that identifies the resource."

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

这篇关于如何使用Java在多个平台上正确加载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:10