读书人

配置的资源文件找不到路径解决思路

发布时间: 2012-02-17 17:50:42 作者: rapoo

配置的资源文件找不到路径
1.读取系统文件中的内容,代码如下:


import java.io.FileInputStream;


import java.util.Properties;

public class Read {
static Properties pro =new Properties();

static FileInputStream fis = null;

public String getPath() {
String path = getClass().getClassLoader().getResource( "my.properties ").getPath();
path = path.substring(1, path.length());

return path;

}

public static void open() throws Exception {
Read r = new Read();
String path = r.getPath();
fis = new FileInputStream(path);
pro.load(fis);
}

public static String getString(String name) throws Exception {
open();
String newname = pro.getProperty(name);

return newname;

}

public static void main(String[] args) throws Exception {

Read r = new Read();
String path = r.getPath();
System.out.println(path);
String url = r.getString( "url ");
System.out.println(url);
}

}


进行单体测试时可以读到url。
打印出的路径: C:/workspace/Test/WebRoot/WEB-INF/classes/my.properties
取得文件内容: jdbc:oracle:thin:@192.168.0.1:1521:test
--------------------------------
2.链接数据库,代码如下
import com.ReadProperties;

import java.io.IOException;
import java.sql.*;

public class getCon {
private String url = null;

private String username = null;

private String password = null;

private String driver = null;

ReadProperties rp = new ReadProperties();

Connection con = null;

public Connection getConn() throws Exception {
driver = Read.getString( "driver ");
url = Read.getString( "url ");
username = Read.getString( "username ");
password = Read.getString( "password ");
try {
try {
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return con;

}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {


// TODO 自动生成方法存根
getCon g = new getCon();
Connection conn = g.getConn();
if (conn != null) {
System.out.println( "Connection Is OK! ");
}
}

}


单体测试通过
---------------------------------

3.但是用eclipse把服务发布到tom5.0中后,就出现问题了

<%
Read rp = new Read();
out.println(rp.getPath());
getCon g = new getCon();
Connection con = g.getConn();
%>

打印出的路径是:C:/Program%20Files/Apache%20Software%20Foundation/Tomcat%205.0/webapps/Test/WEB-INF/classes/my.properties

系统提示找不到这个文件!

急!............

望指点!..........

[解决办法]
不能有空格
你这样读取 new FileInputStream( "my.properties ");
直接读取包名加文件名
[解决办法]
基本上这个是不太可能的,除非你指定目录文件才可以.如:
FileInputStream fis = new FileInputStream( "c://my.properties ");

读书人网 >J2SE开发

热点推荐