Researched by Eric D. Larson
July 2002
Question
How can I read the resources that I package with my MIDlets?
Answer
While MIDP provides methods for loading Images, it doesn't include a specific mechanism for loading files of arbitrary types. There's a simple workaround, though, that's based on three straightforward things you can do:
- You can package any type of file in the JAR file that makes up your MIDlet suite.
- You can open an InputStream to any file in your res directory.
- You can read a resource file using the
getResourceAsStream() method.
This example reads a text file into a StringBuffer, but you could easily modify it to read other types of files, including those containing binary data.
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ReadFile extends MIDlet {
public void startApp() {
try {
Class c = this.getClass();
InputStream is = c.getResourceAsStream("/thisfile.txt");
StringBuffer str = new StringBuffer();
byte b[] = new byte[1];
while ( is.read(b) != -1 ) {
str.append(new String(b));
}
is.close();
System.out.println(str);
}
catch (IOException e) {
e.printStackTrace();
}
}
public void destroyApp(boolean b) {}
public void pauseApp() {}
}
|
Acknowledgments
Thank you to member Jouster for the solution to this problem.
Back To Top
|
|