|
Pers.narod.ru. Тексты. Java2ME. Простой файловый менеджер на Java2ME |
Приложение умеет листать стандартными средствами Java2ME файловую систему телефона, просматривать файлы и их свойства.
Требует профиля MIDP2.0/CLDC1.1, подключения расширения PDA Profile for Java2ME (JSR-75). Компилировалось в WTK 2.2.
import java.util.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class midlet extends MIDlet implements CommandListener {
private String currDirName;
private Command view = new Command("Просмотреть", Command.ITEM, 1);
private Command creat = new Command("Новый", Command.ITEM, 2);
private Command creatOK = new Command("OK", Command.OK, 1);
private Command prop = new Command("Свойства", Command.ITEM, 2);
private Command back = new Command("Назад", Command.BACK, 2);
private Command exit = new Command("Выход", Command.EXIT, 3);
private TextField nameInput; // Новое имя
private ChoiceGroup typeInput; // Тип файла
private final static String[] attrList = { "Чтение", "Запись", "Скрытый" };
private final static String[] typeList = { "Файл", "Папка" };
private final static String[] monthList = {
"янв", "фев", "мар", "апр",
"мая", "июн", "июл", "авг",
"сен", "окт", "ноя", "дек" };
private Image dirIcon, fileIcon;
private Image[] iconList;
// Каталог верхнего уровня
private final static String UP_DIRECTORY = "..";
//Виртуальный "родитель", содержащий все rootы
private final static String MEGA_ROOT = "/";
//Строка-разделитель
private final static String SEP_STR = "/";
//Символ-разделитель
private final static char SEP = '/';
public midlet() {
currDirName = MEGA_ROOT;
try {
dirIcon = Image.createImage("/icons/dir.png");
} catch (IOException e) {
dirIcon = null;
}
try {
fileIcon = Image.createImage("/icons/file.png");
} catch (IOException e) {
fileIcon = null;
}
iconList = new Image[] { fileIcon, dirIcon };
}
public void startApp() {
try {
showCurrDir();
} catch (SecurityException e) {
Alert alert = new Alert("Ошибка",
"Нет доступа",
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
Form form = new Form("Нет соединения");
form.append(new StringItem(null,
"Нет прав запустить этот мидлет. "
+ "Подпишите его или измените настройки безопасности"));
form.addCommand(exit);
form.setCommandListener(this);
Display.getDisplay(this).setCurrent(alert, form);
} catch (Exception e) {
e.printStackTrace();
}
}
public void pauseApp() {
}
public void destroyApp(boolean cond) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
if (c == view) {
List curr = (List)d;
final String currFile = curr.getString(curr.getSelectedIndex());
new Thread(new Runnable() {
public void run() {
if (currFile.endsWith(SEP_STR) || currFile.equals(UP_DIRECTORY)) {
traverseDirectory(currFile);
} else {
// Показать содержимое
showFile(currFile);
}
}
}).start();
} else if (c == prop) {
List curr = (List)d;
String currFile = curr.getString(curr.getSelectedIndex());
showProperties(currFile);
} else if (c == creat) {
createFile();
} else if (c == creatOK) {
String newName = nameInput.getString();
if (newName == null || newName.equals("")) {
Alert alert = new Alert("Ошибка",
"Имя файла пусто. Пожалуйтса, введите его",
null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
Display.getDisplay(this).setCurrent(alert);
} else {
// Создать файл в отдельнос потоке
// и отключить все команды кроме Выхода
executeCreateFile(newName, typeInput.getSelectedIndex() != 0);
Display.getDisplay(this).getCurrent().removeCommand(creatOK);
Display.getDisplay(this).getCurrent().removeCommand(back);
}
} else if (c == back) {
showCurrDir();
} else if (c == exit) {
destroyApp(false);
}
}
//Создание файла в другом потоке
private void executeCreateFile(final String name, final boolean val) {
new Thread(new Runnable(){
public void run(){
createFile(name, val);
}
}).start();
}
//Посмотреть текущий каталог
void showCurrDir() {
Enumeration e;
FileConnection currDir = null;
List browser;
try {
if (MEGA_ROOT.equals(currDirName)) {
e = FileSystemRegistry.listRoots();
browser = new List(currDirName, List.IMPLICIT);
} else {
currDir = (FileConnection)Connector.open("file://localhost/" +
currDirName);
e = currDir.list();
browser = new List(currDirName, List.IMPLICIT);
// Не root - добавить UP_DIRECTORY
browser.append(UP_DIRECTORY, dirIcon);
}
while (e.hasMoreElements()) {
String fileName = (String)e.nextElement();
if (fileName.charAt(fileName.length()-1) == SEP) {
// Каталог
browser.append(fileName, dirIcon);
} else {
// Файл
browser.append(fileName, fileIcon);
}
}
browser.setSelectCommand(view);
browser.addCommand(prop);
//Не позволяем создавать в корне
if (!MEGA_ROOT.equals(currDirName)) {
browser.addCommand(creat);
}
browser.addCommand(exit);
browser.setCommandListener(this);
if (currDir != null) {
currDir.close();
}
Display.getDisplay(this).setCurrent(browser);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
void traverseDirectory(String fileName) {
//Если каталог, сменить и показать
if (currDirName.equals(MEGA_ROOT)) {
if (fileName.equals(UP_DIRECTORY)) {
// из MEGA_ROOT вверх некуда
return;
}
currDirName = fileName;
} else if (fileName.equals(UP_DIRECTORY)) {
// Вверх на шаг
int i = currDirName.lastIndexOf(SEP, currDirName.length()-2);
if (i != -1) {
currDirName = currDirName.substring(0, i+1);
} else {
currDirName = MEGA_ROOT;
}
} else {
currDirName = currDirName + fileName;
}
showCurrDir();
}
void showFile(String fileName) {
try {
FileConnection fc = (FileConnection)
Connector.open("file://localhost/" + currDirName + fileName);
if (!fc.exists()) {
throw new IOException("Файл не существует");
}
InputStream fis = fc.openInputStream();
byte[] b = new byte[1024];
int length = fis.read(b, 0, 1024);
fis.close();
fc.close();
TextBox viewer = new TextBox("Просмотреть файл: " + fileName, null, 1024,
TextField.ANY | TextField.UNEDITABLE);
viewer.addCommand(back);
viewer.addCommand(exit);
viewer.setCommandListener(this);
if (length > 0) {
viewer.setString(new String(b, 0, length));
}
Display.getDisplay(this).setCurrent(viewer);
} catch (Exception e) {
Alert alert = new Alert("Ошибка",
"Нет доступа к файлу " + fileName
+ " в папке " + currDirName
+ "\nИсключение: " + e.getMessage(),
null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
Display.getDisplay(this).setCurrent(alert);
}
}
void showProperties(String fileName) {
try {
if (fileName.equals(UP_DIRECTORY)) {
return;
}
FileConnection fc = (FileConnection)Connector.open("file://localhost/"
+ currDirName + fileName);
if (!fc.exists()) {
throw new IOException("Файл не существует");
}
Form props = new Form("Свойства: " + fileName);
ChoiceGroup attrs = new ChoiceGroup("Атрибуты:", Choice.MULTIPLE,
attrList, null);
attrs.setSelectedFlags(new boolean[] {fc.canRead(),
fc.canWrite(),
fc.isHidden()});
props.append(new StringItem("Расположение:", currDirName));
props.append(new StringItem("Тип: ", fc.isDirectory() ?
"Папка": "Файл"));
props.append(new StringItem("Изменен:",myDate(fc.lastModified())));
props.append(attrs);
props.addCommand(back);
props.addCommand(exit);
props.setCommandListener(this);
fc.close();
Display.getDisplay(this).setCurrent(props);
} catch (Exception e) {
Alert alert = new Alert("Ошибка",
"Нет доступа к файлу " + fileName
+ " в папке " + currDirName
+ "\nИсключение: " + e.getMessage(),
null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
Display.getDisplay(this).setCurrent(alert);
}
}
void createFile() {
Form creator = new Form("Новый файл");
nameInput = new TextField("Введите имя", null, 256, TextField.ANY);
typeInput = new ChoiceGroup("Введите тип файла", Choice.EXCLUSIVE,
typeList, iconList);
creator.append(nameInput);
creator.append(typeInput);
creator.addCommand(creatOK);
creator.addCommand(back);
creator.addCommand(exit);
creator.setCommandListener(this);
Display.getDisplay(this).setCurrent(creator);
}
void createFile(String newName, boolean isDirectory) {
try {
FileConnection fc = (FileConnection) Connector.open("file:///" +
currDirName +
newName);
if (isDirectory) {
fc.mkdir();
} else {
fc.create();
}
showCurrDir();
} catch (Exception e) {
String s = "Не могу создать файл '" + newName + "'";
if (e.getMessage() != null && e.getMessage().length() > 0) {
s += "\n" + e;
}
Alert alert = new Alert("Ошибка", s, null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
Display.getDisplay(this).setCurrent(alert);
// Восстановить командыЮ удаленные в commandAction()
Display.getDisplay(this).getCurrent().addCommand(creatOK);
Display.getDisplay(this).getCurrent().addCommand(back);
}
}
private String myDate(long time) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(time));
StringBuffer sb = new StringBuffer();
sb.append(cal.get(Calendar.HOUR_OF_DAY));
sb.append(':');
sb.append(cal.get(Calendar.MINUTE));
sb.append(':');
sb.append(cal.get(Calendar.SECOND));
sb.append(',');
sb.append(' ');
sb.append(cal.get(Calendar.DAY_OF_MONTH));
sb.append(' ');
sb.append(monthList[cal.get(Calendar.MONTH)]);
sb.append(' ');
sb.append(cal.get(Calendar.YEAR));
return sb.toString();
}
}
Скомпилированный мидлет SimpleBrowser в архиве ZIP (6 Кб)
Исходники проекта (WTK 2.2) (6 Кб)
Моя статья о начале работы с Java2ME и WTK
|
|