2011-04-01 32 views
1

我必须使用文件才能工作。前64字节必须是标题。所以我必须先读取64个字节,然后读取到文件结尾。我如何使用J2ME读写文件?如何在第一个64字节之后读取文件的其余部分?

完全读取一个文件是:

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

并充分写入文件是:

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

回答

1

阅读整个文件,就像你这样做。书写时

// Assuming `str` contains the data read from file 
String header=str.substring(0,64); 
String the_rest_of_file=str.substring(64); 

如果要更改文件的东西,但不是在头,你不真的有跳过 64字节:
然后用这个分裂从文本中读取数据。只需编写相同的标题然后修改后的数据:

// Change `the_rest_of_file` somehow 
// ... 
os.write(header.getBytes()); 
os.write(the_rest_of_file.getBytes()); 
+0

这是个好主意。谢谢。但是如何在64字节之后写入? – 2011-04-01 16:54:09

+0

编辑更多信息的答案。请接受它,如果你觉得它有用 – 2011-04-01 17:03:14

0

使用:

DataInputStream.skipBytes() 
+0

谢谢。如果我只想读写第一个64字节,我该如何阅读? – 2011-04-01 16:40:22

相关问题