做一个网站的计数器,原理是在FILTER内设置一个静态变量。。因为要放服务器上去,所以只能选择相对路径
Long count;
init(){
//读取文件,将读取出来的数值保存到count
}distory(){
//将count保存到文件
}我将init方法和destory方法贴出来。对于这个相对路径我是唉。。我用的tomcat
public void destroy() {
BufferedWriter bw;
System.out.println("destory");
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("./count.txt"))));
bw.write(count+"");
System.out.println("destory over");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}public void init(FilterConfig arg0) throws ServletException {
getDate();
try {
this.count = getCount();
} catch (IOException e) {
count = new Long(0);
}
}
public Long getCount() throws IOException{
Long count;
File file = new File("./count.txt");//这里的路径,我头疼啊,总是读取出错。
if (!file.exists()) {
file.createNewFile();
System.out.println("create file");
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String content = br.readLine();
if (content == null) {
count = new Long(0);
} else {
count = Long.parseLong(content);
}
br.close();
System.out.println(count);
return count; }
Long count;
init(){
//读取文件,将读取出来的数值保存到count
}distory(){
//将count保存到文件
}我将init方法和destory方法贴出来。对于这个相对路径我是唉。。我用的tomcat
public void destroy() {
BufferedWriter bw;
System.out.println("destory");
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("./count.txt"))));
bw.write(count+"");
System.out.println("destory over");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}public void init(FilterConfig arg0) throws ServletException {
getDate();
try {
this.count = getCount();
} catch (IOException e) {
count = new Long(0);
}
}
public Long getCount() throws IOException{
Long count;
File file = new File("./count.txt");//这里的路径,我头疼啊,总是读取出错。
if (!file.exists()) {
file.createNewFile();
System.out.println("create file");
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String content = br.readLine();
if (content == null) {
count = new Long(0);
} else {
count = Long.parseLong(content);
}
br.close();
System.out.println(count);
return count; }
InputStream in = this.getClass().getClassLoader().getResourceAsStream(filename);
把文件放到classpath能找到的地方就可以。
直接
String tempPath = System.getProperty("user.dir") + System.getProperty("file.separator")+ "count.txt"
File file = new File(tempPath);
ServletContext中一个getContextPath()方法得到的是你的web应用的根目录,例如:/test。
然后你就可以定位你的文件的位置了!
config.getServletContext().getRealPath("./count.txt");