【发布时间】:2010-03-07 19:39:19
【问题描述】:
我有以下代码:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class FileConnection extends MIDlet implements CommandListener, Runnable {
private Command exit, start;
private Display display;
private Form form;
public FileConnection ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Write To File");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(form);
}
public void run(){
try{
javax.microedition.io.file.FileConnection filecon =
(javax.microedition.io.file.FileConnection)
Connector.open("file:///root1/photos/fisier.txt", Connector.WRITE);
OutputStream out = filecon.openOutputStream();
PrintStream output = new PrintStream( out );
output.println( "This is a test." );
out.close();
filecon.close();
Alert alert = new Alert("Completed", "Data Written", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( ConnectionNotFoundException error )
{
Alert alert = new Alert(
"Error", "Cannot access file.", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( IOException error )
{
Alert alert = new Alert("Error", error.toString(), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
new Thread(this).start();
}
}
}
如您所见,我正在尝试通过模拟器在文本文件中编写一些内容。我在一个单独的线程中运行该代码,以避免在运行时出现该警告。我在 C:\Program Files\WTK2.5.2_01\j2mewtk_template\appdb\DefaultColorPhone\filesystem\root1\photos 中有一个名为 fisier.txt 的文件。当我尝试运行此代码并按“开始”时,我在问题“J2ME...Midlet Suite 想要编写本地文件系统”时点击“是”。可以更新您的文件吗?是/否'。我在屏幕上显示 java.io.IOException:,仅此而已!..
怎么了?为什么我得到那个错误?我在任何地方都找不到关于如何写入本地 .txt 文件的工作代码。
不知道我的代码有什么问题?
【问题讨论】:
-
当您捕捉到异常时,调用 Throwable.printStackTrace() 以确保您知道实际抛出它的方法。使用 Connector.READ_WRITE。确保您的模拟器安全策略在运行未签名的 MIDlet(我假设您的 MIDlet 是)时提供对文件系统的完全访问权限。先关闭 PrintStream。用结果更新您的问题。