獲取文件路徑報空指針

String filePath =request.getSession().getServletContext().getRealPath("/");

提示這行代碼報空指針。

總代碼是這樣的:

 //得到文件夾路徑
	String filePath1 = request.getSession().getServletContext().getRealPath("/");
	String filePath = filePath1+"prCodeImages";
        System.out.println(filePath);
        File prCodeFile = new File(filePath);
        if(!prCodeFile .exists()  && !prCodeFile .isDirectory()){
        	prCodeFile .mkdir(); 
        }
按道理說當文件不存在,我判斷了並新建,所以應該不可能出錯。

這裏報空指針的原因其實和獲取文件沒什麼關係了。

是getsession時報錯,當沒有session對象時getsession是會報錯的。

String filePath1 = request.getSession(true).getServletContext().getRealPath("/");
這樣加個true就沒事了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章