我在 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));
        }
    }