小谈——读取web资源文件的方式和路径问题

读取web资源文件的方式

 a): 采用servletContext对象获得.  

  优点: 任意文件,任意路径都可获得

  缺点: 必须在web环境下

// 拿到全局对象
        ServletContext sc = this.getServletContext();

        // 获取p1.properties文件的路径
        String path = sc.getRealPath("/WEB-INF/classes/p1.properties");

 b): 采用resourceBundle获得

  优点: 非web环境下

  缺点: 只能获取properties文件

// 采用resourceBunble拿取资源文件:获取p1资源文件的内容 默认路径是src,对用到web环境就是classes目录
    public void test21() {
        // 拿取ResourceBundle对象(专门用来获取properties文件的信息)
        ResourceBundle rb = ResourceBundle.getBundle("p1");
        // 拿取文件中的内容
        System.out.println(rb.getString("k"));
    }

 c): 采用类加载器获得

优点: 任意路径,任意文件(文件不能过大)

// 获取类加载器的方式
        /*
         * 1. 通过类名 ServletContext.class.getClassLoader() 2. 通过对象
         * this.getClass().getClassLoader() 3. Class.forName()
         * 获取Class.forName("ServletContext7").getClassLoader()
         */
        URL url  = this.getClass().getClassLoader().getResource("p1.properties") ;       
        String path = url.getPath() ;

读取web资源文件

读取工程中的资源文件,Java中的IO流其实就可以完成,下面使用Java中的IO流完成读取资源文件。

  • 首先在Web工程中,创建四个资源文件。

² Web工程的根目录下创建1.txt。

² Web工程的WebRoot目录下创建2.txt。

² Web工程的WebRoot目录的WEB-INF目录下创建3.txt。

² Web工程的src目录下创建4.txt。

  • 创建一个Java文件用于读取上述的四个资源文件。
public class ReaderFileTest {
    // 编写readfile()方法完成资源文件的读取工作.
    public static void readfile(String fileName) throws Exception{
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
    
    public static void main(String[] args) throws Exception {
        // 读取1.txt
        String filename1 = "1.txt";
        readfile(filename1);
        // 读取2.txt
        String filename2 = "WebRoot/2.txt";
        readfile(filename2);
        // 读取3.txt
        String filename3 = "WebRoot/WEB-INF/3.txt";
        readfile(filename3);
        // 读取4.txt
        String filename4 = "src/4.txt";
        readfile(filename4);
    }
}
  • 运行该Java文件会在控制台打印响应信息。

如果要想利用Servlet API的内容来读取Web工程中的资源文件,又要如何来做呢?ServletContext对象的getRealPath()方法可以来完成此项工作。

  • 创建一个自定义Servlet,使用ServletContext对象的getRealPath()方法来完成读取资源文件。
public class ReadFileServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/4.txt");
        IOUtils.copy(in, out);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

还有一种通用的方法:利用Class类的getResource()方法也可以完成读取资源文件的工作。

public class ReadFileServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 利用类加载器读取Web工程的资源文件
        String filename = ReadFileServlet.class.getResource("/4.txt").getFile();
        InputStream in = new FileInputStream(new File(filename));
        IOUtils.copy(in, out);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

IOUtils.copy(in, out)用来复制文件的工具类

    public class IOUtils{
public void copy(InputStream in,OutputStream out) throws IOException{
        //创建具体的流对象
                BufferedInputStream buffis = new BufferedInputStream(in);
                BufferedOutputStream buffos = new BufferedOutputStream(out);
                
                byte [] buf = new byte[1024];
                int len = 0;
                while((len = buffis.read(buf)) !=-1){           
                    buffos.write(buf, 0, len);
                    buffos.flush();
                }
                in.close();
                out.close();
    }
}
天行健,君子以自强不息
原文地址:https://www.cnblogs.com/god-y-l/p/6847774.html