在java web開發中,經常會涉及到檔案的讀寫問題,而由于部署在tomcat上之後,檔案的目錄結構會發生一些變化,是以正常的擷取相對或絕對路徑的方式用在此處會導緻擷取不到檔案的尴尬局面,下面便介紹一下在servlet中如何讀取WEB-INF下的txt檔案。
下圖為項目路徑,而這裡要實作的便是使用CounterServlet來讀取WEB-INF目錄下的count.txt檔案。
前面一步一步講原理,完整代碼放在最後面
首先擷取路徑,正常的相對路徑在這裡無效,在tomcat上部署後目錄結構變了
String path = this.getServletContext().getRealPath("/WEB-INF/count.txt");
擷取到路徑後建立File對象
File file = new File(path);
建立一個BufferedReader對象用來讀取檔案
再建立一個輸入字元流對象
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
利用輸入字元流對象建立BufferedReader對象執行個體
然後進行資料的讀取
String line = "";
//讀取一行的寫法
line = br.readLine();
//讀取多行的寫法
while( (line = br.readLine()) != null ){
...
}
最後關閉BufferedReader
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
完整代碼:
String path = this.getServletContext().getRealPath("/WEB-INF/count.txt");
File file = new File(path);
BufferedReader br = null;
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
br = new BufferedReader(reader);
String line = "";
line = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}