tags:

views:

2083

answers:

1

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();
}
+4  A: 

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.

Joachim Sauer
StringBuilder is not available in J2ME?
PhiLho
StringBuilder isn't, but StringBuffer is. J2ME is stuck in some very strange pre-Java 2 world (no collections framework for petes sake!)
Joachim Sauer
It's not pre-Java 2, it's pre-J2SE 1.5. J2ME is defined based on the 1.4 standard.
Fostah
@Fostah: are you sure? The collections framework was in 1.2, if I remeber correctly and that one is missing from J2ME (only Vector and Hashtable are available, which existed before the collections framework).
Joachim Sauer