日期:2014-05-16  浏览次数:20323 次

JSR75学习笔记

这段时间因为开发上要用到本地文件,因此开始接触Jsr75的包,Jsr75分两个部分,一部分是File,即本地文件系统,一部分是PIM,说白了就是电话本之类的信息,我先学习的是File部分,通过import javax.microedition.io.file.*里的包,可以实现自由访问本机的文件系统,就跟Windos里的资源管理器一样,在这里我介绍几个我写的方法

一.获取指定路径的目录和文件列表

/* 目录文件列表 */
public Vector list(String path) {
	try {
		FileConnection fc = (FileConnection) (Connector.open(path));
		if (fc.exists()) {
			Vector listVec = new Vector(0, 1);
			Enumeration en = fc.list();
			while (en.

			hasMoreElements()) {
				listVec.addElement((String) (en.nextElement()));
			}
			return listVec;
		} else
			return null;
	} catch (Exception e) {
		System.

		out.println("listErr:" + e.toString());
		return null;
	}
}

??

方法里的path参数就是要查找的路径,比如file:///c:/pictures/,切记,如果是目录Path,那么后面的/一定不能省,否则会查找不到内容。这个方法返回的是一个包含了指定Path下的所有目录名和文件名的向量。

二.建立或者保存一个文件到指定路径

/* 保存文件 */
public void saveFile(String path, byte[] fileData) {
	try {
		FileConnection fc = (FileConnection) (Connector.open(path));
		fc.create();
		fc.setWritable(true);
		OutputStream os = fc.openOutputStream();
		os.write(fileData);
		os.

		close();
	} catch (Exception e) {
		System.out.println("saveFileErr:" + e.toString());
	}
}

?

fileData是需要保存的文件内容,可以是声音,也可以是图像,或者文字之类

三.删除指定文件

/* 删除文件 */
public void deleteFile(String path) {
	try {
		FileConnection fc = (FileConnection) (Connector.open(path));
		if (fc.exists())
			fc.delete();
	} catch (Exception e) {
		System.out.println("deleteFileErr:" + e.

		toString());
	}
}

?

这个方法就不用多解释了

四.读取指定文件

/* 读取文件 */
public byte[] readFile(String path) {
	try {
		FileConnection fc = (FileConnection) (Connector.open(path));
		if (fc.exists()) {
			InputStream is = fc.openInputStream();
			byte[] temp = new byte[is.available()];
			is.read(temp);
			is.close();
			return temp;
		} else
			return null;
	} catch (Exception e) {
		System.out.println("readFileErr:" + path + e.toString());
		return null;

	}
}

?

此方法也不用多解释了。

以上是关于文件操作的最基本的一些功能,也是第一期的学习笔记研究到的内容,更多的内容,过几天继续研究继续写吧,呵呵。

原文转自J2ME开发网----作者:刀剑啸