Reading a text file in J2ME

I am trying to read a resource (asdf.txt), but if the file is more than 5000 bytes (for example), 4700 pieces of a null character are inserted at the end of the content variable. Is there any way to remove them? (or set the correct buffer size?)

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();
}
+3
source share
1 answer

The easiest way is to do the right thing: use 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 specifically determine the encoding of the text file you want to read. In the above example, this will be THE_ENCODING.

And note that both your code and this sample code work equally well in Java SE and J2ME.

+7
source

Source: https://habr.com/ru/post/1706262/


All Articles