J2ME讀取本地檔案的方法 public byte[] readFile(String filepath) {
byte data[] = null;
try {
FileConnection fc = (FileConnection) Connector.open(filepath);
DataInputStream dis = fc.openDataInputStream();
int ch;// 每次讀出的資料
int index = 0;// 讀取的資料的總索引
int len = 1024;// 放資料的空間不夠時,每次擴充空間的大小為1024位元組
byte buf[];// 暫時存放從data[]拷貝出來的資料
data = new byte[len];// 先初步設定一個1k的記憶體空間
while ((ch = dis.read()) != -1) {
data[index] = (byte) ch;
index++;
if (index >= len) {
len += 1024;
buf = new byte[len];
System.arraycopy(data, 0, buf, 0, index);
data = null;
data = buf;
}
}
// 此時data[]的長度可能要比實際資料多,最後的一些位元組可能是一些無效的資料,去掉無效資料
if ((index % 1024) == 0) {
buf = new byte[index];// index的值是資料的實際大小
System.arraycopy(data, 0, buf, 0, index);
data = null;
data = buf;
}
if (dis != null) {
dis.close();
dis = null;
}
if (fc != null) {
fc.close();
fc = null;
}
} catch (IOException e) {
e.printStackTrace();
} return data;
}