J2ME / Blackberry - 如何读/写文本文件?

时间:2009-10-05 10:38:42

标签: blackberry file-io java-me text-files jsr75

请给我一个黑莓应用程序中读/写文本文件的示例代码。

2 个答案:

答案 0 :(得分:29)

我的字符串读/写文件的代码片段:

private String readTextFile(String fName) {
  String result = null;
  FileConnection fconn = null;
  DataInputStream is = null;
  try {
   fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
   is = fconn.openDataInputStream();
   byte[] data = IOUtilities.streamToBytes(is);
   result = new String(data);
  } catch (IOException e) {
   System.out.println(e.getMessage());
  } finally {
   try {
    if (null != is)

     is.close();
    if (null != fconn)
     fconn.close();
   } catch (IOException e) {
    System.out.println(e.getMessage());
   }
  }
  return result;
 }

private void writeTextFile(String fName, String text) {
  DataOutputStream 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());
  } 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());
   }
  }
 }

答案 1 :(得分:4)

相关问题