2008-06-13
文件读写乱码笔记
关键字: j2me fileconnection最近在做音乐歌词读写的项目的时候,遇到一个很烦的问题,我们在读取保存在本地的歌词的时候出现乱码,在有的手机上面没有这个问题,在有的手机上就有这个问题。当时是我负责这块,郁闷了半天,专门为这个问题,查了各个手机的api支持的字符集,可是最后没有很好的解决这个问题,先是直接读到一个byte[]里面再new (byte[],"UTF-8")乱码问题大大的有,后来在读出的时候也是将流转化为DataInputStream,再去readUTF(),还是乱码。
上面是小插曲,其实解决这样子的问题很简单,只要控制写和读的一致性就没有问题了。
比如:
写操作
public synchronized void saveLyricFile(String data, String name) {
if (data == null || data.length() == 0) {
return;
}
OutputStream os = null;
DataOutputStream dos = null;
FileConnection fc = null;
try {
fc = (FileConnection) Connector.open(
"file:///" + musicSavePath+ name);
if (fc.exists()) {
//存在就不保存了
fc.close();
fc = null;
return;
}
fc.create();
os = fc.openOutputStream();
dos = new DataOutputStream(os);
dos.writeUTF(data);
dos.close();
os.close();
fc.close();
fc = null;
} catch (IOException ex) {
try {
fc.close();
dos.close();
os.close();
fc.close();
fc = null;
} catch (IOException ex1) {
ex1.printStackTrace();
}
ex.printStackTrace();
} finally {
try {
dos.close();
os.close();
fc.close();
fc = null;
} catch (IOException ex1) {
ex1.printStackTrace();
}
}
}
在读保存的文件的时候就可以直接
DataInputStream dis = new DataInputStream(is);
String lrcText = dis.readUTF();
这样子就没有什么乱码问题了。


评论