public byte[] read_a_file() {
byte[] data = new byte[2000];
try {
Class c = this.getClass();
InputStream is = c.getResourceAsStream("file.txt");
DataInputStream dis = new DataInputStream(is);
dis.readFully(data);
is.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return data;
}
> Thanks a lot, but how can I know the exact number of
> bytes of the file to create the byte array?
You can't! that's why the above method sucks!
Use a ByteArrayOutputStream to read the file:
public static byte[] readfile(String file){
ByteArrayOutputStream bin = new ByteArrayOutputStream();
InputStream is = getClass().getResourceAsStream(file);
byte[] buffer = new byte[512];
int rd;
while((rd=is.read(buffer))!=-1){
bin .write(buffer,0,rd);
}
return file.toByteArray();
}
Ok, thanks a lot I will use it and test it. Can you please now teach me how to save a file instead of reading it. Its the first time I see that way and I am learning j2me by my own for my job.
In j2SE I always used the FileInputStream and FileOutputStream to handle files and I never understood well the ByteArray Streams.
A MIDlet has only access to a little area of the phone for security reasons, it's called the record management store (aka RMS) and its used to allow a MIDlet to write it's own data.
The class javax.microedition.rms.RecordStore and related are used for this.
If you want more advanced features like exploring the whole device, you should use the FileConnection package:
http://developers.sun.com/techtopics/mobility/apis/articles/fileconnection/