大家好,我在Eclipse中键了一个web工程test,然后在test/src下放了一个Excel文件,即test/src/excel.xls,然后在程序中想要读取它,使用"/excel.xls"路径不行吗?后来放到WebRoot下,即test/WebRoot/excel.xls,还是不行,请问在eclipse中"/"代表什么路径呢?我的目的是部署到服务器上,我tomcat服务器的appBase是webapps目录,而我直接把那个excel文件放在该目录下,然后在程序中用路径"/excel.xls",还是不行,请指教,谢谢~谢谢~~
比如 你有个文件夹 myspace 在文件夹下面有 a文件夹 a 文件夹下面又有 c文件夹
然后c文件夹下面有 d.jsp
你就可以这样获取路径了:/myspace/a/c/d.jsp
这样就找到了你需要的d.jsp了。
java.net.URL url = ClassName.class.getResource(""); // ClassName为这个调用类的名字
String pathPrefix = url.getPath().substring(); // 字符串截取
excelFilePath = pathPrefix + "excel.xls"; // 拼出绝对路径。
"/excel.xls"这样读取就正确
test
|__src
| |______testjava
| |_____Test.java
|
|__WebRoot
|____aaa
|________excel.xls现在要在Test.java中读取excel.xls,这个路径如何取?谢谢~~
2."我tomcat服务器的appBase是webapps目录,而我直接把那个excel文件放在该目录下",这样是不成的,如果没有你自己的test的目录,tomcat自带的root目录你也可以用,把root下的东东清空,把你的项目中WebRoot下的所有东东放进去也可以
request.getContextPath()+"/aaa/excel.xls";就可以得到excel.xls
package netbar;/* 访问数据库工具类
*/
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;public class Dbconn {
private static Properties props = new Properties();
static {
InputStream in = Dbconn.class.getResourceAsStream("db.properties");
try {
props.load(in);
Class.forName(props.getProperty("driver"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} public static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(props.getProperty("url"), props
.getProperty("user"), props.getProperty("pwd"));
} catch (Exception e) {
e.printStackTrace();
}
return con;
} public static void close(Object o) {
try {
if (o instanceof ResultSet) {
((ResultSet) o).close();
} else if (o instanceof Statement) {
((Statement) o).close();
} else if (o instanceof Connection) {
((Connection) o).close();
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void close(ResultSet rs, Statement stmt, Connection con) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
"/test/aaa/excel.xls",而且%TOMCAT_HOME%/webapps/test/aaa/excel.xls确实存在,但是调用
new File("/test/aaa/excel.xls").exists()返回的就是false,为什么呢?这路径应该没问题吧。请指教。
|__src
| |______testjava
| |_____Test.java
| |_____ excel.xls
|
|
|__WebRoot
就是这样的,你试试!
对,应该是这样的,但是我这边还是不行,new File("...").exists()是判断当前文件是否存在,如果在就是true,但我每次都是false,而如果用了绝对路径,就是true了。太奇怪了。
然后直接/aaa/excel.xls 使用应该是没问题。