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

來源:互聯網
上載者:User

標籤:api   com   全域   檔案中   etc   flush   close   throws   http   

讀取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工程中,建立四個資源檔。

2 在Web工程的根目錄下建立1.txt。

2 在Web工程的WebRoot目錄下建立2.txt。

2 在Web工程的WebRoot目錄的WEB-INF目錄下建立3.txt。

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

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.