file manager j2me sorce code download
import java.io.*;
import javax.microedition.io.file.FileSystemListener;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.*;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
public class FileManagerMidlet extends MIDlet implements FileSystemListener{
private Display display;
private FileManager manager;
private SysRootsList rootsList;
private DirList dirList;
private CreateForm createForm;
private PropertyForm propertyForm;
private ReaderBox readerBox;
private Alert errAlert;
private Alert processAlert;
private String copyFile = "";
public FileManagerMidlet(){
manager = new FileManager();
FileSystemRegistry.addFileSystemListener(this);
}
public void startApp() {
display = Display.getDisplay(this);
try{
if(rootsList == null){
rootsList = new SysRootsList(this,manager.list());
}
display.setCurrent(rootsList);
}catch(IOException ioe){
showError("error!"+ioe.toString(),rootsList);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
manager.release();
}
public void exit(){
destroyApp(true);
notifyDestroyed();
}
public void displayDirList(String dir) throws IOException{
manager.changeDirectory(manager.getName(dir));
if(manager.isDriverRoot()){
display.setCurrent(rootsList);
}else{
String[] files = manager.list();
if(dirList == null){
dirList = new DirList(this);
}
dirList.update(manager.getCurrDir(),files);
display.setCurrent(dirList);
}
}
public void delete(String fileName){
try{
manager.delete(fileName);
String[] files = manager.list();
dirList.update(manager.getCurrDir(),files);
display.setCurrent(dirList);
}catch(IOException ioe){
showError("error\n"+ioe.toString(),dirList);
}
}
public void displayCreateForm(){
if(createForm == null){
createForm = new CreateForm(this);
}
createForm.setBackScreen(dirList);
display.setCurrent(createForm);
}
public void displayPropertyForm(String f,Displayable backScreen){
try{
File file = manager.getProperty(f);
if(propertyForm == null){
propertyForm = new PropertyForm(this);
}
propertyForm.update(file,backScreen);
display.setCurrent(propertyForm);
}catch(IOException ioe){
showError("error\n"+ioe.toString(),backScreen);
}
}
public void showError(String errMsg,Displayable nextScreen){
if(errAlert == null){
errAlert = new Alert("error",errMsg,null,AlertType.ERROR);
errAlert.setTimeout(Alert.FOREVER);
}
errAlert.setString(errMsg);
display.setCurrent(errAlert,nextScreen);
}
public void showProcessInfo(String msg){
if(processAlert == null){
processAlert = new Alert("error..");
Gauge gauge = new Gauge(null,false,100,1);
processAlert.setIndicator(gauge);
processAlert.setTimeout(100000);
}
processAlert.setString(msg);
display.setCurrent(processAlert);
}
public void backTo(Displayable backScreen){
display.setCurrent(backScreen);
}
public void create(File file){
try{
manager.create(file);
String[] files = manager.list();
dirList.update(manager.getCurrDir(),files);
display.setCurrent(dirList);
}catch(IOException ioe){
showError("error"+ ioe.toString(),dirList);
}
}
public void rootChanged(int state,java.lang.String rootName){
Alert alert = new Alert("Root changed","",null,AlertType.INFO);
if(state == FileSystemListener.ROOT_ADDED){
alert.setString("root Added: "+rootName);
}else if(state == FileSystemListener.ROOT_REMOVED){
alert.setString("Root removed: "+rootName+".");
}
alert.setTimeout(2000);
String[] sr = manager.getSysRoots();
rootsList.update(sr);
display.setCurrent(alert);
}
public void copy(String fileName){
copyFile = manager.getCurrDir() + fileName;
}
public void paste() throws IOException{
String desFile = manager.getName(copyFile);
manager.copy(copyFile,desFile);
String[] files = manager.list();
dirList.update(manager.getCurrDir(),files);
display.setCurrent(dirList);
}
public void openTextFile(String fileName,Displayable backScreen) throws IOException{
if(!fileName.endsWith(".txt")){
throw new IOException("error");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manager.read(fileName,baos);
String fileContent = new String(baos.toByteArray(),"UTF-8");
System.out.println(fileContent);
if(readerBox == null){
readerBox = new ReaderBox(this);
}
readerBox.setContent(fileName,fileContent);
readerBox.setBackScreen(backScreen);
display.setCurrent(readerBox);
}
private class FileManager {
public final String DRIVER_ROOT = "/";
private final String URL_HEAD = "file://";
public final String PARENT_DIR = "..";
private String strSep = "/";
private char chSep = '/';
private String currDir;
private FileConnection fconn;
private Vector sysRoots;
public FileManager(){
currDir = DRIVER_ROOT;
sysRoots = createSysRoots();
}
public Vector createSysRoots(){
Enumeration e = null;
e = FileSystemRegistry.listRoots();
Vector v = new Vector();
String rootName = null;
while(e.hasMoreElements()){
rootName = (String)e.nextElement();
v.addElement(rootName);
}
return v;
}
private Vector getCurrDirFiles() throws IOException{
if(currDir == DRIVER_ROOT){
return sysRoots;
}
Enumeration e = null;
e = fconn.list();
String fileName;
Vector v = new Vector();
v.addElement(PARENT_DIR);
while(e.hasMoreElements()){
fileName = (String)e.nextElement();
v.addElement(fileName);
}
return v;
}
public String[] list() throws IOException{
Vector v = getCurrDirFiles();
String[] fileArray = new String[v.size()];
v.copyInto(fileArray);
return fileArray;
}
public String[] getSysRoots(){
sysRoots = createSysRoots();
String[] r = new String[sysRoots.size()];
sysRoots.copyInto(r);
return r;
}
public void create(File file) throws IOException{
if(currDir==DRIVER_ROOT){
throw new IOException("dir:"+file);
}
String fileUrl = URL_HEAD+currDir+file.getName();
FileConnection fc = (FileConnection)Connector.open(fileUrl);
if(fc.exists()){
throw new IOException("file connection");
}
if(file.isDirectory()){
fc.mkdir();
}else{
fc.create();
}
fc.setReadable(file.canRead());
fc.setWritable(file.canWrite());
fc.setHidden(file.isHidden());
fc.close();
}
public void delete (String fileName) throws IOException{
if(currDir == DRIVER_ROOT){
throw new IOException("sds:"+fileName);
}
String fileUrl = URL_HEAD+currDir+fileName;
FileConnection fc = (FileConnection)Connector.open(fileUrl);
if(!fc.canWrite()){
throw new IOException("sds: "+fileName+" sdds");
}
if(fc.isDirectory()){
Enumeration e = fc.list();
if(e.hasMoreElements()){
throw new IOException("sds:"+fileName);
}
}
fc.delete();
fc.close();
}
public File getProperty(String fileName)throws IOException{
File f = new File(fileName);
String fileUrl = URL_HEAD+currDir+fileName;
FileConnection fc = (FileConnection)Connector.open(fileUrl);
f.setReadable(fc.canRead());
f.setWritable(fc.canWrite());
f.setHidden(fc.isHidden());
f.setLastModify(fc.lastModified());
fc.close();
return f;
}
public void copy(String srcFile,String newFileName)throws IOException{
String srcFileUrl = URL_HEAD+srcFile;
System.out.println("src:"+srcFileUrl);
FileConnection srcFc = (FileConnection)Connector.open(srcFileUrl);
if(!srcFc.exists()||!srcFc.canRead()){
throw new IOException("sd:\""+srcFile+"\"ds");
}
if(srcFc.isDirectory()){
throw new IOException("sd:\""+srcFile+"\"eeer");
}
if(currDir == DRIVER_ROOT){
throw new IOException("errrrrrr");
}
String desFileUrl = URL_HEAD+currDir+newFileName;
System.out.println("des: "+desFileUrl);
FileConnection desFc = (FileConnection)Connector.open(desFileUrl);
if(desFc.exists()){
throw new IOException("errrrrrrrr");
}
desFc.create();
InputStream is = srcFc.openInputStream();
OutputStream os = desFc.openOutputStream();
byte[] buf = new byte[200];
int n = -1;
while((n = is.read(buf,0,buf.length))!= -1){
os.write(buf, 0, n);
}
is.close();
os.close();
srcFc.close();
desFc.close();
}
public void changeDirectory(String dirName)throws IOException{
if(dirName==PARENT_DIR){
if(currDir==DRIVER_ROOT){
}else{
if(manager.getPath(currDir).equals(DRIVER_ROOT)){
currDir = DRIVER_ROOT;
fconn.close();
fconn = null;
}else{
fconn.setFileConnection(PARENT_DIR);
currDir = manager.getPath(currDir);
}
}
}else{
if(currDir==DRIVER_ROOT){
currDir = currDir+dirName;
String dirUrl = URL_HEAD+ currDir;
fconn = (FileConnection)Connector.open(dirUrl);
}else{
currDir = currDir+dirName;
fconn.setFileConnection(dirName);
}
}
}
public String getCurrDir(){
return currDir;
}
public void release(){
try{
if(fconn!=null){
fconn.close();
}
}catch(IOException ioe){
}
}
public String getName(String pathName){
int index = pathName.lastIndexOf(chSep,pathName.length()-2);
String name = pathName;
if(index != -1){
name = pathName.substring(index+1);
}
return name;
}
public String getPath(String pathName){
int index = pathName.lastIndexOf(chSep,pathName.length()-2);
String path = "";
if(index != -1){
path = pathName.substring(0,index+1);
}
return path;
}
public boolean isDirectory(String dir){
return dir.endsWith(strSep)||dir.endsWith(PARENT_DIR);
}
public boolean isDriverRoot(){
return currDir.equals(DRIVER_ROOT);
}
public long read(String file,ByteArrayOutputStream baos)throws IOException{
String fileUrl = URL_HEAD+currDir+file;
FileConnection fc = (FileConnection)Connector.open(fileUrl);
if(!fc.exists()){
throw new IOException("er:\""+file+"\"e");
}
if(fc.isDirectory()){
throw new IOException("re:\n"+file+"e");
}
if(!fc.canRead()){
throw new IOException("er: "+file+" er");
}
InputStream is = fc.openInputStream();
int n = -1;
int total = 0;
byte[] buf = new byte[250];
while((n = is.read(buf, 0, buf.length))!=-1){
baos.write(buf, 0, n);
total+=n;
}
is.close();
fc.close();
return total;
}
}
private class DirList extends List implements CommandListener{
private FileManagerMidlet midlet;
private Image imgFile;
private Image imgDir;
private Command cmdExit = new Command("Exit",Command.EXIT,1);
private Command cmdOk = new Command("Ok",Command.OK,2);
private Command cmdDelete = new Command("Delete",Command.SCREEN,3);
private Command cmdCreate = new Command("Create",Command.SCREEN,3);
private Command cmdProperty = new Command("Property",Command.SCREEN,3);
private Command cmdCopy = new Command("Copy",Command.SCREEN,3);
private Command cmdPaste = new Command("Paste",Command.SCREEN,3);
private String[] files;
private String dir;
public DirList(FileManagerMidlet midlet){
super(null,IMPLICIT);
this.midlet = midlet;
try{
imgFile = Image.createImage("/file.png");
imgDir = Image.createImage("/dir.png");
}catch(IOException ioe){
}
addCommand(cmdExit);
addCommand(cmdOk);
addCommand(cmdDelete);
addCommand(cmdCreate);
addCommand(cmdProperty);
addCommand(cmdCopy);
addCommand(cmdPaste);
setCommandListener(this);
}
public void update(String dir,String[] files){
this.dir = dir;
setTitle(dir);
deleteAll();
this.files = files;
for(int i = 0;i<files.length;i++){
if(manager.isDirectory(files[i])){
append(files[i],imgDir);
}else{
append(files[i],imgFile);
}
}
}
public void commandAction(Command cmd,Displayable d){
if(cmd==cmdExit){
midlet.exit();
}else if(cmd == cmdOk){
Thread t = new Thread(){
public void run(){
int index = getSelectedIndex();
try{
if(manager.isDirectory(files[index])){
midlet.displayDirList(files[index]);
}else{
midlet.openTextFile(files[index], DirList.this);
}
}catch(IOException ioe){
midlet.showError(ioe.toString(), DirList.this);
}
}
};
t.start();
}else if(cmd == cmdDelete){
Thread t = new Thread(){
public void run(){
int index = getSelectedIndex();
midlet.delete(files[index]);
}
};
t.start();
}else if(cmd == cmdCreate){
midlet.displayCreateForm();
}else if(cmd == cmdProperty){
Thread t = new Thread(){
public void run(){
int index = getSelectedIndex();
System.out.println(files[index]);
midlet.displayPropertyForm(getString(index), DirList.this);
}
};
t.start();
}else if(cmd == cmdCopy){
int index = getSelectedIndex();
midlet.copy(files[index]);
}else if(cmd== cmdPaste){
Thread t =new Thread(){
public void run(){
try{
midlet.paste();
}catch(IOException ioe){
midlet.showError(":\n"+ioe.toString(), DirList.this);
}
}
};
t.start();
}
}
}
public class CreateForm extends Form implements CommandListener{
private FileManagerMidlet midlet;
private TextField tfFileName;
private ChoiceGroup cgType;
private String[] typeName = {"File","Folder"};
private ChoiceGroup cgProperty;
private String[] propertyName = {"Readable","Writable","Hidden"};
private Command cmdBack = new Command("Back",Command.BACK,1);
private Command cmdCreate = new Command("Create",Command.SCREEN,2);
private Displayable backScreen;
public CreateForm(FileManagerMidlet midlet){
super("");
this.midlet = midlet;
tfFileName = new TextField("File name: ","",30,TextField.ANY);
append(tfFileName);
cgType = new ChoiceGroup("Type:",Choice.EXCLUSIVE);
for(int i=0;i<typeName.length;i++){
cgType.append(typeName[i], null);
}
append(cgType);
cgProperty = new ChoiceGroup("Property",Choice.MULTIPLE);
for(int i=0;i<propertyName.length;i++){
cgProperty.append(propertyName[i], null);
}
append(cgProperty);
addCommand(cmdBack);
addCommand(cmdCreate);
setCommandListener(this);
}
public void setBackScreen(Displayable backScreen){
this.backScreen = backScreen;
}
public void commandAction(Command cmd,Displayable d){
if(cmd==cmdCreate){
midlet.showProcessInfo("........");
Thread t = new Thread(){
public void run(){
String name = tfFileName.getString();
if(name.endsWith("/")){
midlet.showError("", CreateForm.this);
return;
}
int index = cgType.getSelectedIndex();
if(index==1){
name +="/";
}
boolean[] shux = new boolean[3];
cgProperty.getSelectedFlags(shux);
File f = new File(name);
f.setReadable(shux[0]);
f.setWritable(shux[1]);
f.setHidden(shux[2]);
midlet.create(f);
}
};
t.start();
}else if(cmd == cmdBack){
midlet.backTo(backScreen);
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
*
*/
public class File {
private String name;
private boolean readable;
private boolean writable;
private boolean hidden;
private long modifyDate;
public File(String name){
this.name = name;
}
public String getName(){
return name;
}
public boolean isDirectory(){
return name.endsWith("/");
}
public boolean canRead(){
return readable;
}
public void setReadable(boolean b){
readable = b;
}
public boolean canWrite(){
return writable;
}
public void setWritable(boolean b){
writable = b;
}
public boolean isHidden(){
return hidden;
}
public void setHidden(boolean b){
hidden = b;
}
public long getLastModify(){
return modifyDate;
}
public void setLastModify(long l){
modifyDate = l;
}
}
public class PropertyForm extends Form implements CommandListener{
private FileManagerMidlet midlet;
private StringItem siName;
private StringItem siReadable;
private StringItem siWritable;
private StringItem siHidden;
private StringItem siModifyDate;
private Displayable backScreen;
private Command cmdBack = new Command("Back",Command.BACK,1);
public PropertyForm(FileManagerMidlet midlet){
super("");
this.midlet = midlet;
siName = new StringItem("Name:","");
siReadable = new StringItem("Readable","");
siWritable = new StringItem("Writable","");
siHidden = new StringItem("Hidden","");
siModifyDate = new StringItem("ModifyDate","");
append(siName);
append(siReadable);
append(siWritable);
append(siHidden);
append(siModifyDate);
addCommand(cmdBack);
setCommandListener(this);
}
public void update(File f,Displayable backScreen){
this.backScreen = backScreen;
siName.setText(f.getName());
if(f.canRead()){
siReadable.setText("Yes");
}else{
siReadable.setText("No");
}
if(f.canWrite()){
siWritable.setText("Yes");
}else{
siWritable.setText("No");
}
if(f.isHidden()){
siHidden.setText("Yes");
}else{
siHidden.setText("No");
}
long d = f.getLastModify();
Calendar cale = Calendar.getInstance();
cale.setTime(new Date(d));
String t = cale.get(Calendar.YEAR)+"Year"
+(cale.get(Calendar.MONTH)+1)+"Month"
+cale.get(Calendar.DAY_OF_MONTH)+"Day"
+cale.get(Calendar.HOUR_OF_DAY)+"Hour"
+cale.get(Calendar.MINUTE)+"Minute";
siModifyDate.setText(t);
}
public void commandAction(Command cmd,Displayable d){
if(cmd==cmdBack){
System.out.println("OK"+midlet);
Display display = Display.getDisplay(midlet);
display.setCurrent(backScreen);
}
}
}
public class ReaderBox extends TextBox implements CommandListener{
private FileManagerMidlet midlet;
private Command cmdBack = new Command("Back",Command.BACK,1);
private Displayable backScreen;
public ReaderBox(FileManagerMidlet midlet){
super("","",2000,TextField.ANY|TextField.UNEDITABLE);
this.midlet =midlet;
addCommand(cmdBack);
setCommandListener(this);
}
public void setContent(String fileName,String content){
setTitle("File:"+fileName);
setMaxSize(content.length());
setString(content);
}
public void setBackScreen(Displayable d){
this.backScreen = d;
}
public void commandAction(Command cmd,Displayable d){
if(cmd==cmdBack){
midlet.backTo(backScreen);
}
}
}
public class SysRootsList extends List implements CommandListener{
private FileManagerMidlet midlet;
private Command cmdExit = new Command("Exit",Command.EXIT,1);
private Command cmdSelect = new Command("Select",Command.ITEM,2);
private Image img;
private String[] roots;
public SysRootsList(FileManagerMidlet midlet,String[] roots){
super("/",IMPLICIT);
this.midlet = midlet;
try{
img = Image.createImage("/derive.png");
}catch(IOException ioe){
}
update(roots);
addCommand(cmdExit);
addCommand(cmdSelect);
setCommandListener(this);
}
public void show(){
Display display = Display.getDisplay(midlet);
display.setCurrent(this);
}
public void update(String[] roots){
this.roots = roots;
deleteAll();
for(int i=0;i<roots.length;i++){
append(roots[i],img);
}
}
public void commandAction(Command cmd,Displayable d){
if(cmd == cmdExit){
midlet.exit();
}else if(cmd== cmdSelect){
Thread t = new Thread(){
public void run(){
try{
int index = getSelectedIndex();
midlet.displayDirList(roots[index]);
}catch(IOException ioe){
midlet.showError(ioe.toString(), SysRootsList.this);
}
}
};
t.start();
}
}
}
}
Thank you so much, saved me a lot of time.
ReplyDeleteThank you ! I need a code of web browser for j2me apps. Can you tell me please ?
ReplyDelete