简体   繁体   English

在J2ME中读取文本文件

[英]Reading text file in J2ME

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. 我正在尝试读取资源(asdf.txt),但是如果文件大于5000字节,例如,在content变量的末尾插入了4700个空字符。 Is there any way to remove them? 有什么办法可以删除它们? (or to set the right size of the buffer?) (或设置缓冲区的正确大小?)

Here is the code: 这是代码:

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

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().

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. 在上面的示例中,它将是THE_ENCODING。

And note that both your code and this example code work equally well on Java SE and J2ME. 请注意,您的代码和本示例代码在Java SE和J2ME上均能很好地工作。

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

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