简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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