在J2ME中读取文本文件 [英] Reading text file in J2ME

查看:153
本文介绍了在J2ME中读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取资源(asdf.txt),但如果文件大于5000字节,(例如)将4700个空字符插入到内容变量的末尾。有没有办法删除它们? (或设置正确的缓冲区大小?)

I'm trying to read a resource (asdf.txt), but if the file is bigger than 5000 bytes, (for example) 4700 pieces of null-character inserted to the end of the content variable. Is there any way to remove them? (or to set the right size of the buffer?)

以下是代码:

String content = "";
try {
    InputStream in = this.getClass().getResourceAsStream("asdf.txt");
    byte[] buffer = new byte[5000];
    while (in.read(buffer) != -1) {
        content += new String(buffer);
    }
} catch (Exception e) {
    e.printStackTrace();
}


推荐答案

最简单的方法是做正确的事情:使用Reader读取文本数据:

The simplest way is to do the correct thing: Use a Reader to read text data:

String content = "";
Reader in = new InputStreamReader(this.getClass().getResourceAsStream("asdf.txt"), THE_ENCODING);
StringBuffer temp = new StringBuffer(1024);
char[] buffer = new char[1024];
int read;
while ((read=in.read(buffer, 0, buffer.len)) != -1) {
  temp.append(buffer, 0, read);
}
content = temp.toString().

不是你肯定应该定义你想要的文本文件的编码阅读。在上面的示例中,这将是THE_ENCODING。

Not that you definitely should define the encoding of the text file you want to read. In the example above that would be THE_ENCODING.

请注意,您的代码和此示例代码在Java SE和J2ME上同样运行良好。

And note that both your code and this example code work equally well on Java SE and J2ME.

这篇关于在J2ME中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆