Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中如何獲取 asset 目錄下的 ini 檔案

編輯:關於 Android 程式設計

1、獲取資源的輸入流

假設資源位於 assets 目錄下,可用 Context.getAssets().open("sample.txt") 取得輸入流。若要遞迴遍歷並複製整個 assets 目錄到裝置,可以像下面這樣判斷是目錄還是檔案:

public void deepFile(Context ctxDealFile, String path) {

try {

String str[] = ctxDealFile.getAssets().list(path);

if (str.length > 0) {// 如果是目錄

File file = new File("/data/" + path);

file.mkdirs();

for (String string : str) {

path = path + "/" + string;

System.out.println("zhoulc:\t" + path);

deepFile(ctxDealFile, path);

path = path.substring(0, path.lastIndexOf('/'));

}

} else {// 如果是檔案

InputStream is = ctxDealFile.getAssets().open(path);

FileOutputStream fos = new FileOutputStream(new File("/data/" + path));

byte[] buffer = new byte[1024];

int count = 0;

while (true) {

count++;

int len = is.read(buffer);

if (len == -1) {

break;

}

fos.write(buffer, 0, len);

}

is.close();

fos.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

2、具體例子

以下示範讀取 assets 中 ini/boot.ini 的內容,解析出 boot 與 bootIP 的設定值:

private void getBootUrl(Context context) throws IOException {

Log.d(TAG, "getBootUrl() start");

InputStream is = null;

BufferedReader in = null;

try {

is = context.getAssets().open("ini/boot.ini");

in = new BufferedReader(new InputStreamReader(is));

} catch (IOException e1) {

e1.printStackTrace();

Log.d(TAG, e1.getMessage());

}

StringBuffer sb = new StringBuffer();

String temp = null;// 存放每行讀取的內容

int line = 1;

String[] sbStrs = new String[] {};// 以「=」為分隔符將 string 分割

try {

while ((temp = in.readLine()) != null) {

if (temp.contains("boot")) {

sb.append(temp.substring((temp.indexOf("t") + 2)) + " ");// 從「=」等分隔符以後截取子串保存

line++;

while ((temp = in.readLine()) != null) {

if (temp.contains("bootIP")) {

sb.append(temp.substring((temp.indexOf("P") + 2)) + " ");

break;

} else {

line++;

}

break;

}

}

in.close();

is.close();

} catch (IOException e) {

e.printStackTrace();

bootUrl = "";

Log.d(TAG, e.getMessage());

} finally {

if (in != null) {

in.close();

}

}

sbStrs = sb.toString().split(" ");

bootUrl = sbStrs[0];

bootIpUrl = sbStrs[1];

Log.d(TAG, "getBootUrl() end");

}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved