Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

java - how to read/write text file in j2me

i want to know how to read and write text to a .txt file in j2me help me thanks...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public String readFile(String path)
    {
        InputStream is = null;
        FileConnection fc = null;
        String str = "";
        try
        {
            fc = (FileConnection)Connector.open(path, Connector.READ_WRITE);

            if(fc.exists()) 
            {
                int size = (int)fc.fileSize();
                is= fc.openInputStream();
                byte bytes[] = new byte[size];
                is.read(bytes, 0, size);
                str = new String(bytes, 0, size);
            }
        } 
        catch (IOException ioe) 
        {
        Alert error = new Alert("Error", ioe.getMessage(), null, AlertType.INFO);
        error.setTimeout(1212313123);
        Display.getDisplay(main).setCurrent(error);} 
        finally 
        { 
            try 
            { 
                if (null != is) 
                    is.close(); 
                if (null != fc) 
                    fc.close(); 
            } 
            catch (IOException e) 
            { 
                System.out.println(e.getMessage()); 
            } 
        } 
        return str;
    }  

    void writeTextFile(String fName, String text) 
    { 
        OutputStream os = null; 
        FileConnection fconn = null; 
        try 
        { 
            fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE); 
            if (!fconn.exists()) 
                fconn.create();

            os = fconn.openDataOutputStream();
            os.write(text.getBytes()); 
            fconn.setHidden(false);
//          fconn.setReadable(true);
        } 

        catch (IOException e) 
        { 
            System.out.println(e.getMessage()); 
        } 
        finally 
        { 
            try 
            { 
                if (null != os) 
                    os.close(); 
                if (null != fconn) 
                    fconn.close(); 
            } 
            catch (IOException e) 
            { 
                System.out.println(e.getMessage()); 
            } 
        } 
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...