程序读取了WEB-INF目录下的txt文件,但我即使把txt文件里面的内容改掉了,程序读取到的内容没有变,似乎被记录住了,这是怎么一个情况?怎样解决这个问题?先谢园友了。
无代码无真相
1 /* 2 * (non-Javadoc) 3 * 关闭Tomcat时,destroy()方法就会把serveltContext的属性写进WEB-INF下的recoed.txt文件 4 * 开启Tomcat时,init()方法会把record.txt文件中的第一行信息读出,并把这个信息放进servletContext里 5 */ 6 package com.vv.view; 7 8 import java.io.BufferedReader; 9 import java.io.BufferedWriter; 10 import java.io.FileNotFoundException; 11 import java.io.FileReader; 12 import java.io.FileWriter; 13 import java.io.IOException; 14 import java.io.PrintWriter; 15 16 import javax.servlet.ServletException; 17 import javax.servlet.http.HttpServlet; 18 import javax.servlet.http.HttpServletRequest; 19 import javax.servlet.http.HttpServletResponse; 20 21 public class InitServlet extends HttpServlet { 22 23 24 public void destroy() { 25 26 // 得到record文件的绝对路径 27 String filePath = this.getServletContext().getRealPath("record.txt"); 28 29 System.out.print("yoyo"); 30 31 // 把servletContext的属性写进record文件 32 try { 33 FileWriter fileWriter = new FileWriter(filePath); 34 BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); 35 36 bufferedWriter.write( (String) this.getServletContext() 37 .getAttribute("num")); 38 39 bufferedWriter.close(); 40 fileWriter.close(); 41 42 } catch (Exception e) { 43 // TODO Auto-generated catch block 44 e.printStackTrace(); 45 } 46 47 } 48 49 public void doGet(HttpServletRequest request, HttpServletResponse response) 50 throws ServletException, IOException { 51 52 response.setContentType("text/html"); 53 PrintWriter out = response.getWriter(); 54 55 } 56 57 public void doPost(HttpServletRequest request, HttpServletResponse response) 58 throws ServletException, IOException { 59 60 this.doGet(request, response); 61 } 62 63 public void init() throws ServletException { 64 65 // 得到记录文件的绝对路径,然后进行写和读 66 String filePath = (String) this.getServletContext().getRealPath( 67 "record.txt"); 68 System.out.println("haha"); 69 70 try { 71 FileReader fileReader = new FileReader(filePath); 72 BufferedReader bufferedReader = new BufferedReader(fileReader); 73 String num = bufferedReader.readLine(); 74 75 this.getServletContext().setAttribute("num", num); 76 77 System.out.println(num); 78 bufferedReader.close(); 79 fileReader.close(); 80 81 } catch (Exception e) { 82 e.printStackTrace(); 83 } 84 85 } 86 87 }
你好,这是代码,那个record.txt文件呢,就只有一行数据,就是一个数字“0”。
程序很简单,有些注释没改过来。