Sau đây là ví dụ tôi viết cho phần này, tạm thời tôi post lên để trả lời gấp cho câu hỏi của các sinh viên khóa 06 đang thực hiện nhiệm vụ nghiên cứu về FileConnection, khi nào có thời gian tôi sẽ chú thích chi tiết cho ví dụ này.
/* DO NOT REMOVE THESE BELOW COMMENT
* Example for Java@FITHOU
* Using FileConnection (JSR75)
* Created by huudungle on 2010 Apr 03
* Published on www.huudungle.net
* */
import java.io.*;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class GCFMidlet extends MIDlet {
private Form form;
private StringItem si;
private void loadFileContent(){
//<drive>:\WTK<xx>\appdb\<device>\filesystem\root1\
//where <xx> is your Wireless Toolkit version
// <device> is your device you choose to run your MIDlet on emulator
//make sure that the above path existed
String URL = "file:///root1/test.txt";
try {
FileConnection fc =(FileConnection)Connector.open(URL, Connector.READ_WRITE);
if (!fc.exists()){
fc.create();
DataOutputStream dos = fc.openDataOutputStream();
dos.writeUTF("Hello from MIDlet");
dos.flush();
si.setText("written");
}else{
DataInputStream dis = fc.openDataInputStream();
String content = dis.readUTF();
si.setText(content);
}
fc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
si.setText(e.getMessage());
}
}
public GCFMidlet() {
// TODO Auto-generated constructor stub
form =new Form("File Connection");
si=new StringItem("Content", "");
form.append(si);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
Display display = Display.getDisplay(this);
display.setCurrent(form);
loadFileContent();
}
}