小談——讀取web資源文件的方式和路徑問題

讀取web資源文件的方式

 a): 採用servletContext對象得到.  web

  優勢: 任意文件,任意路徑均可得到工具

  缺點: 必須在web環境下this

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

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

 b): 採用resourceBundle得到url

  優勢: 非web環境下spa

  缺點: 只能獲取properties文件code

// 採用resourceBunble拿取資源文件:獲取p1資源文件的內容 默認路徑是src,對用到web環境就是classes目錄
    public void test21() {
        // 拿取ResourceBundle對象(專門用來獲取properties文件的信息)
        ResourceBundle rb = ResourceBundle.getBundle("p1");
        // 拿取文件中的內容
        System.out.println(rb.getString("k"));
    }

 c): 採用類加載器得到對象

優勢: 任意路徑,任意文件(文件不能過大)blog

// 獲取類加載器的方式
        /*
         * 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。get

² 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();
    }
}
相關文章
相關標籤/搜索