【发布时间】:2013-08-11 23:51:02
【问题描述】:
我在 Eclipse 中开发 web 动态项目。一个名为“users.txt”的文件位于类文件夹(WEB-INF/classes/users.txt)下。
如何在类(基类,而不是 servlet 类)中获取此文件的相对路径?我将使用该路径附加几行文本。
Christian,这是用于阅读的代码。问题是我不知道如何在具有相对路径的同一文件中创建用于写入(输出)的对象。
public Products(){
try{
InputStream in = getClass().getClassLoader().getResourceAsStream("products.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
readProducts(br);
in.close();
br.close();
}catch(Exception e){
System.out.println("File doesn't exists");
}
}
public void readProducts(BufferedReader in) throws NumberFormatException, IOException{
String id="";
String name="";
double price=0;
StringTokenizer st;
String line;
while((line=in.readLine())!=null){
st=new StringTokenizer(line,";");
while(st.hasMoreTokens()){
id=st.nextToken();
name=st.nextToken();
price=Double.parseDouble(st.nextToken());
}
products.put(id,new Product(id,name,price));
}
}
【问题讨论】:
-
您能否发布一些代码,至少您到目前为止尝试过什么?
-
您正在寻找错误方向的解决方案。您不应该在运行时写入部署文件夹,更不用说部署类路径了。将文件放在部署文件夹外的固定位置。额外的好处是您当前的问题可以通过这种方式立即解决。顺便说一句,通常的做法是使用 SQL 数据库来处理这类东西。