动态小数据操作是WEB开发中不可避免的,这就涉及到数组 哈希表 属性类等几个功能;本文提供本人常用语法和简单解释:
一般数组定义
//定义数组catalogs
public static final String[] catalogs =
{"Business","Entertainment","Law","Real Estate","Medical","Services","Computers & Internet","Food","Other"};
//在form中逐个显示数组内容
<SELECT name="catalog">
<%
for (int i = 0; i < catalogs.length; i++)
{
String catalog=(String)catalogs[i];
if (i==catalogid) //catalogid是需要selected的int类型
out.println("<OPTION value="+i+" selected>"+catalog+"</OPTION>");
else
out.println("<OPTION value="+i+">"+catalog+"</OPTION>");
}
%>
</SELECT>
vector
vector是java的动态数组的功能, 随着更多元素加入其中,数组变的更大.
public Vector getGraphFile(Hashtable hashtable)
{
Vector vector = new Vector();
for(Enumeration enumeration = hashtable.keys(); enumeration.hasMoreElements();)
{
String s1 = (String)enumeration.nextElement();
if (isGraphFile(s1))
{
vector.addElement(s1);
}
}
return vector;
}
本例是将hashtable 的关键词转为vector数组. 要遍历vector或hashtable使用java的Enumeration
for (Enumeration e = v.elements(); e.hasMoreElements();)
{
out.println((String)e.nextElement());
}
这是将Vector中的值输出.注意使用类型强制转换.
Hashtable
Hashtable是一个关键字对应关键值的表,使用该表,可以迅速索引到某个值.这个表很好用,补充Vector不足.
Hashtable hashtable=new Hashtable();
hashtable.put("1","男");
hashtable.put("2","女");
out.println("性别是"+(String)hashtable.get("2"))
如果一个关键字对应多个关键值,而且这几个关键词中不一定是字符形,可能包含其他复杂类型:
//加入数据
hashtable.put(name, new UploadedFile(dir.toString(), fileName,filePart.getContentType()));
//取数据
UploadedFile file = (UploadedFile)hashtable.get(name);
return file.getFilesystemName(); //得fileName
return file.getContentType(); //得type
//类 UploadedFile定义:
class UploadedFile {
private String dir;
private String filename;
private String type;
UploadedFile(String dir, String filename, String type) {
this.dir = dir;
this.filename = filename;
this.type = type;
}
public String getContentType() {
return type;
}
public String getFilesystemName() {
return filename;
}
public File getFile() {
if (dir == null || filename == null) {
return null;
}
else {
return new File(dir + File.separator + filename);
}
}
台湾蔡学镛先生有专门一篇 谈论Collection 文章,有兴趣者可进一步研究.
Properties
下面是获取系统属性的方法
import java.util.Properties;
public class getSystemProperties
{
public static void main(String args[])
{
//通过获得系统属性构造属性类 prop
Properties prop = new Properties(
System.getProperties() );
//在标准输出中输出系统属性的内容
prop.list(System.out);
}
//根据获取的系统属性确定程序执行流程
}
属性文件的操作:
Properties prop = new Properties();
try
{
FileInputStream fis=new FileInputStream(“firstProp.txt”);
}catch (FileNotFoundException ex) {
throw new Exception("error:"+ex.getMessage());
}
prop.load(fis);
out.println(getProperty("fruits"))
Properties可以对下列文件格式进行操作:
firstProp.txt
Truth = Beauty
Truth:Beauty
Truth :Beauty
fruits apple, banana, pear,
cantaloupe, watermelon,
kiwi, mango