日期:2014-05-20  浏览次数:20735 次

J2ME的写文件操作

?

?

        FileConnection cfc = null;
        OutputStream output = null;
        try {
            cfc = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
            if (!cfc.exists()) {
                cfc.create();
            }
            output = cfc.openOutputStream(cfc.fileSize());//从文件尾追加写
            output.write(out.getBytes("UTF-8")); //必须用UTF-8编码,否则中文会乱码
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cfc != null)
                try {
                    cfc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

?

?

注意点:

?

  1. ?FileConnection的openOutputStream方法可以接受一个long值,表示从这个位置开始追加输出,如果不指定文件内容会被重写
  2. OutputStream的write(byte[] bytes)方法,byte数组如果是中文的话,必须是utf8编码,否则会乱码

?


?