4

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();
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Jani
  • 111
  • 1
  • 8

1 Answers1

8

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

public String readFromFile(String filename, String enc) throws Exception {
    String content = "";
    Reader in = new 
    InputStreamReader(this.getClass().getResourceAsStream(filename), enc);
    StringBuffer temp = new StringBuffer(1024);
    char[] buffer = new char[1024];
    int read;
    while ((read=in.read(buffer, 0, buffer.length)) != -1) {
        temp.append(buffer, 0, read);
    }
    content = temp.toString();
    return content;
}

Note that you definitely should define the encoding of the text file you want to read.

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

Burak
  • 2,251
  • 1
  • 16
  • 33
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • StringBuilder is not available in J2ME? – PhiLho Apr 11 '09 at 08:54
  • 2
    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 Apr 11 '09 at 14:36
  • It's not pre-Java 2, it's pre-J2SE 1.5. J2ME is defined based on the 1.4 standard. – Fostah Apr 13 '09 at 13:32
  • 1
    @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 Apr 13 '09 at 20:15