如何使用java进行数据库连接从Web内容文件夹中读取文件

时间:2012-03-19 17:14:35

标签: java mysql jsp

txt文件,我将所有数据库设置称为数据库名称,服务器名称,用户名,密码,此文件位于Web内容目录-config.txt中, 但它无法从java类文件中读取。

public Statement myStatement()抛出异常{

    File file=new File("DBSetting.txt");
    FileInputStream fis = null;                                           // declares a file input stream
    //BufferedInputStream bis = null;
    DataInputStream dis = null;
    BufferedReader buffread=null;
    try{
        fis = new FileInputStream(file);                                   // file inputstream opens file
        dis = new DataInputStream(fis);                              // data input stream extracts data from file input stream
        buffread=new BufferedReader(new BufferedReader(new InputStreamReader(dis)));   // bufferedreader reads data from data input
        //dis = new DataInputStream(bis);
        connection=removeSpaces(buffread.readLine());    // reads data from file into variables
        port=removeSpaces(buffread.readLine());
        database=removeSpaces(buffread.readLine());
        username=removeSpaces(buffread.readLine());
        password=removeSpaces(buffread.readLine());

        System.out.println("DB Settings -:Server Name and SQL Port - " +connection+ ", Port - "+port+", DB Name - "+database+", UserName - "+username+" , PWD-"+password);

        //System.out.println(ay[ay.length-1]);
          //System.out.println(connection);
        dis.close();
    }
    catch(Exception ex){System.out.println(ex);}


    Class.forName("com.mysql.jdbc.Driver").newInstance();

    String url = "jdbc:mysql://"+connection + ":" + port + "/"+database;
    System.out.println(url);
    return DriverManager.getConnection(url, username ,password).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

}

public static String removeSpaces(String s) {                    // removes white spaces present in strings
  StringTokenizer st = new StringTokenizer(s," ",false);
  String t="";
  while (st.hasMoreElements()) t += st.nextElement();
  return t;
}
public static void main(String args[])throws Exception
{
    ConnectionManager con = new ConnectionManager();
    con.myStatement();
}

}

2 个答案:

答案 0 :(得分:0)

很难理解你的问题,但我认为你可以在这里找到你想要的答案: How to load resource from jar file packaged in a war file?

答案 1 :(得分:0)

在webcontent目录中?真?这样终端用户就可以通过URL打开文件。不要公开披露此信息。而是把它放在类路径中。而且还要使它成为正常.properties file,这样您就不需要自己解析文件了。

E.g。 db.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/dbname
username = foo
password = bar

然后您可以按如下方式加载和获取数据:

Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("test.properties"));
String driver = properties.getProperty("driver");
String url = properties.getProperty(url);
String username = properties.getProperty(username);
String password = properties.getProperty(password);
// ...