Search code examples
javajava-me

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

Solution

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