简体   繁体   English

如何在j2me中读/写文本文件

[英]how to read/write text file in j2me

我想知道如何在j2me中读取和写入.txt文件的文本帮助我谢谢...

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()); 
            } 
        } 
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM