如何使用j2me midp2.0读取存储在移动设备中的文本文件?

Sar*_*nan 2 mobile java-me

大家好,

我在j2me midp2.0环境下工作.我的应用程序想要读取存储在移动设备中的文本文件.如何使用j2me以编程方式读取文本文件.请给我一个想法来获取这个.什么是移动设备中的根文件夹放置文本文件以便从j2me应用程序环境访问.

Saravanan.P

oxi*_*gen 5

你需要javax.microedition.io.file.FileConnection

获取根文件夹:

  try {
        Enumeration roots = FileSystemRegistry.listRoots();
        while(roots.hasMoreElements()) {
            System.out.println("Root: file:///"+(String)roots.nextElement());
        }
    } catch(Exception e) {
    }
Run Code Online (Sandbox Code Playgroud)

写入文件

        public void write(String root) {                
        FileConnection fc = null;
        String fName = "test.txt";
        try {
            fc = (FileConnection) Connector.open(root + fName, Connector.READ_WRITE);
            if(!fc.exists()) {
                fc.create();
            }

            DataOutputStream dos = fc.openDataOutputStream();
            dos.writeUTF("test-test");                

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
            } catch (IOException e) { }
        }
}
Run Code Online (Sandbox Code Playgroud)

从文件中读取

public void read(String root) {
        FileConnection fc = null;
        try {
             fc= (FileConnection) Connector.open(root + "test.txt", Connector.READ);
             DataInputStream dis = fc.openDataInputStream();
             String data = dis.readUTF();
             System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
            } catch (IOException e) { }
    }
    }
Run Code Online (Sandbox Code Playgroud)