如何使用java for DB connectivity从web内容文件夹读取文件
txt文件,其中我调用了所有数据库设置,如数据库名、服务器名、用户名、pwd,该文件位于web内容目录-config.txt中, 但它无法读取java类文件 公共语句myStatement()引发异常{如何使用java for DB connectivity从web内容文件夹读取文件,java,mysql,jsp,Java,Mysql,Jsp,txt文件,其中我调用了所有数据库设置,如数据库名、服务器名、用户名、pwd,该文件位于web内容目录-config.txt中, 但它无法读取java类文件 公共语句myStatement()引发异常{ File file=new File("DBSetting.txt"); FileInputStream fis = null; // declares a file input stream
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();
}
}你的问题很难理解,但我想你可以在这里找到你想要的答案:
在webcontent目录中?真正地这样,最终用户就可以通过URL打开文件。不要将此信息公开。而是把它放在类路径中。也可以将其设置为普通,这样您就不需要亲自解析文件 例如,
db.properties
:
driver=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/dbname
用户名=foo
密码=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);
// ...