編輯:關於 Android 程式設計
需要把設定(例如 IP 與連接埠)存成本地 XML。早期的版本每次執行都會重新建立檔案,導致先前寫入的資料被覆蓋。修正後的做法是:檔案不存在就建立並寫入根節點,檔案已存在就解析後再往根節點追加,實現真正的遞增。
public class Doc2Xml {
public static boolean saveParam2Xml(String ip_value, String socket_value) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
File f = new File("../Test/xml/text.xml");
Document document;
if (!f.exists()) {
f.createNewFile();
document = builder.newDocument();
Element configs = document.createElement("configs");
document.appendChild(configs); // 建立根節點
} else {
document = builder.parse(f);
}
// 無論新建或既有,都取得根節點後追加
Element configs = document.getDocumentElement();
Element config = document.createElement("config");
Element ip = document.createElement("ip");
Element socket = document.createElement("socket");
ip.appendChild(document.createTextNode(ip_value));
socket.appendChild(document.createTextNode(socket_value));
config.appendChild(ip);
config.appendChild(socket);
configs.appendChild(config);
return write2Xml(document, f);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return false;
}
}
關鍵在於把「建立」與「追加」的分支收斂到同一段程式碼:新建時先 appendChild 根節點,既有則用 getDocumentElement() 取回同一個根節點,之後的追加邏輯完全共用,不必寫兩份。
public static boolean write2Xml(Document document, File file) {
TransformerFactory factory = TransformerFactory.newInstance();
try {
Transformer transformer = factory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult result = new StreamResult(file);
transformer.transform(domSource, result);
return true;
} catch (TransformerConfigurationException e) {
e.printStackTrace();
return false;
} catch (TransformerException e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
System.out.println(Doc2Xml.saveParam2Xml("10.1.23.2", "8888"));
}
手機端的儲存路徑不建議寫死相對路徑,正式專案應改用 Context.getFilesDir() 取得應用程式私有目錄,並在建立檔案前先確認父目錄存在(呼叫 mkdirs())。另外 DOM 會把整份文件載入記憶體,資料量小沒問題;若日後要寫入大量紀錄,改用 SAX 串流寫出會更省資源。
Android 6.0 執行期授權機制與權限管理實作
6.0 之後,授權邏輯整個換了 Android 6.0(API 23)對權限系統做了一次結構性的改造。只有當你的 targetSdkVersion 設為 23 以上,且應
Android PopupWindow 底部彈出與背景漸暗效果
在 Android 中,Dialog、PopupMenu 與 PopupWindow 都能做出彈出式選單。PopupMenu 適合在按鈕附近顯示簡單選單;PopupWin
Android 自定義 LayoutManager 入門:常見誤區、關鍵 API 與復用真相
自定義 LayoutManager 系列開篇 這篇文章是深入掌握自定義 LayoutManager 系列的第一篇,也是一份學習前的總整理。內容會先釐清常見誤區,再說明背後
Android 免 Root 實作 Traceroute:非 Root 環境下移植可執行檔與腳本
1. 原理思路 想在手机上跑 busybox 或 traceroute,第一个撞到的墙就是文件权限:如果没有 root,你无法改变二进制文件的执行权限。 推送 busyb