I must use a file for work. First 64 byte must be a header. So I must read first 64 bytes and then read to end of file. How can I read and write a file with J2ME?
Read fully a file is that:
FileConnection fconn= (FileConnection) Connector.open(path+fName,Connector.READ);
InputStream is=fconn.openInputStream();
DataInputStream dis = new DataInputStream(is);
int ch;
String str = new String();
while ( (ch = dis.read())开发者_如何学运维 != -1)
{
str+=((char)ch);
}
dis.close();
is.close();
And fully write a file is:
FileConnection fconn= (FileConnection)Connector.open(path+fName,Connector.READ_WRITE);
if(!fconn.exists()){
items.alert=new Alert(" ","Select The Directory",null,AlertType.INFO);
switchDisplayable(items.alert,items.getList());
fconn.create();
}
os = fconn.openDataOutputStream();
fconn.truncate(0);
os.write(text.getBytes());
os.close();
fconn.close();
Read the whole file, like you're doing.
Then use this to split the data read from text:
// Assuming `str` contains the data read from file
String header=str.substring(0,64);
String the_rest_of_file=str.substring(64);
If you want to change something in the file, but not in the header, you don't really have to skip 64 bytes when writing. Just write the same header and then the modified data:
// Change `the_rest_of_file` somehow
// ...
os.write(header.getBytes());
os.write(the_rest_of_file.getBytes());
use:
DataInputStream.skipBytes()
精彩评论