count.java
来自「java的一系列产品中包括jsme,jmse,j2ee,本文件提供j2ee实现的」· Java 代码 · 共 80 行
JAVA
80 行
package examples.jsp.tagext.counter;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* This class synchronizes access to the count hits file.
*/
public class Count {
synchronized static public int getCount(File filestore) {
if (!filestore.exists()) {
return 0;
}
ObjectInputStream os = null;
try {
os = new ObjectInputStream(new FileInputStream(filestore));
int count = os.readInt();
return count;
} catch(IOException e) {
System.out.println("Unable to read from counter file: "+filestore);
return 0;
} finally {
try {
os.close();
} catch(Exception e) {
System.out.println("Unable to close counter file: "+filestore);
e.printStackTrace();
}
}
}
synchronized static public void incCount(File filestore) {
int count = 0;
// Attempt to read the current count from the filestore
if (filestore.exists()) {
// try to read the current count
ObjectInputStream is = null;
try {
is = new ObjectInputStream(new FileInputStream(filestore));
count = is.readInt();
} catch(Exception e) {
System.out.println("Unable to read from counter file: "+filestore);
e.printStackTrace();
} finally {
try {
is.close();
} catch(Exception e) {
System.out.println("Unable to close counter file: "+filestore);
e.printStackTrace();
}
}
}
// Increament the obtained count
count++;
// Now write out the incremented count
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(filestore));
os.writeInt(count);
}catch(Exception e) {
System.out.println("Unable to write to counter file: "+filestore);
e.printStackTrace();
} finally {
try {
os.close();
} catch(Exception e) {
System.out.println("Unable to close output stream to counter file: "+filestore);
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?