一鍵刪除android下面無用資源,一鍵android

來源:互聯網
上載者:User

一鍵刪除android下面無用資源,一鍵android

項目需求一改再改,UI一調再調,結果就是項目中一堆已經用不到但卻沒有清理的垃圾資源,不說工程大小問題,對新進入項目的人或看其他模組的代碼的人來說,這些沒清理的資源可能也可能會帶來困擾,所以最好還是清理掉這些垃圾,對於一個稍微大一點的工程來說,手工清理明顯是不現實的,這就需要一個方法做這些事情。

本人最怕碼字,上面內容引入http://www.cnblogs.com/angeldevil/p/3725358.html

關於android lint的使用,如果不瞭解的請自行去瞭解。

下面是我的清除代碼,主要就是使用dom-節點解析來刪除無用資源,需要引入dom.jar ,建議到這個倉庫去下載http://search.maven.org/,速度還可以。代碼沒有做最佳化,臨時寫的。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

public class CleanResources {

 public static void clearResources(String projectPath, String resultPath)
   throws IOException {
  BufferedReader reader = new BufferedReader(new FileReader(resultPath));
  String line;
  int count = 0;
  while ((line = reader.readLine()) != null) {
   if (line.contains("UnusedResources") && !line.contains("appcompat")
     && !line.contains("res\\values")) {
    count++;
    int end = line.indexOf(":");
    if (end != -1) {
     String file = line.substring(0, end);
     String f = projectPath + file;
     System.out.println(f);
     new File(f).delete();
    }
   }
  }
 }

 public static void doDocCheck(String projectPath, String resultPath)
   throws InterruptedException, IOException {
  String cmd = "cmd /c lint --check \"UnusedResources\" " + projectPath
    + " >" + resultPath;
  Process process = Runtime.getRuntime().exec(cmd);
  System.out.println(cmd);
  String ls;
  BufferedReader bufferedReader = new BufferedReader(
    new InputStreamReader(process.getInputStream()));
  while ((ls = bufferedReader.readLine()) != null) {
   System.out.println(ls);
  }
  process.waitFor();
 }

 public static void checkResource(String resultPath, String checkPath)
   throws IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(
    new FileInputStream(resultPath), "gbk"));
  String line;
  StringBuffer sbf = new StringBuffer();
  sbf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  sbf.append("<resources>\n");
  while ((line = reader.readLine()) != null) {
   if (line.contains("<color") || line.contains("<string")) {
    sbf.append(line);
    if (line.contains("<string-array")) {
     sbf.append("</string-array>");
    }
    sbf.append("\n");
   }
  }
  sbf.append("</resources>");
  // System.out.println(sbf.toString());
  writeFile(checkPath, sbf.toString());
 }

 public static void writeFile(String fileAbsultPath, String content)
   throws IOException {
  OutputStream os = new FileOutputStream(fileAbsultPath);
  os.write(content.getBytes());
  os.close();
 }

 public static void prepairClear(String clearPath, String checkPath)
   throws ParserConfigurationException, SAXException, IOException {
  File fileParent = new File(clearPath);
  File checkFile = new File(checkPath);

  if (fileParent.isDirectory()) {
   for (File file : fileParent.listFiles()) {
    clear(file, checkFile);
   }
  } else {
   clear(fileParent, checkFile);
  }
 }

 public static void clear(File clearFile, File checkFile)
   throws ParserConfigurationException, SAXException, IOException {
  DocumentBuilderFactory builderFactory = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder builder = builderFactory.newDocumentBuilder();
  Document document = builder.parse(clearFile);
  Element rootElement = document.getDocumentElement();
  NodeList childNodes = rootElement.getChildNodes();

  DocumentBuilderFactory builderFactory2 = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder builder2 = builderFactory2.newDocumentBuilder();
  Document document2 = builder2.parse(checkFile);
  Element rootElement2 = document2.getDocumentElement();
  NodeList childNodes2 = rootElement2.getChildNodes();

  for (int i = 0; i < childNodes.getLength(); i++) {
   Node childNode = childNodes.item(i);
   if (childNode.getNodeType() == Node.ELEMENT_NODE) {
    for (int j = 0; j < childNodes2.getLength(); j++) {
     Node childNode2 = childNodes2.item(j);
     if (childNode2.getNodeType() == Node.ELEMENT_NODE) {
      if (childNode
        .getAttributes()
        .getNamedItem("name")
        .getNodeValue()
        .equals(childNode2.getAttributes()
          .getNamedItem("name").getNodeValue())) {
       rootElement.removeChild(childNode);
      }
     }
    }

   }
  }
  StringBuffer sbf = new StringBuffer();
  sbf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  nodeTranserse(rootElement, sbf);
  sbf.append("</" + rootElement.getNodeName() + ">");
  System.out.println(sbf.toString());
  writeFile(clearFile.getAbsolutePath(), sbf.toString());
 }

 public static void nodeTranserse(Node node, StringBuffer sbf) {
  String rNodeName = node.getNodeName();// 當前遍曆元素名稱
  if (node.getNodeType() == Node.ELEMENT_NODE) { // 為節點類型,輸出節點名稱
   sbf.append("<" + rNodeName);
   // System.out.print("<" + rNodeName);
   if (node.hasAttributes()) {
    NamedNodeMap map = node.getAttributes();
    int len = map.getLength();
    for (int i = 0; i < len; i++) {
     sbf.append(" ");
     Node attr = map.item(i);
     sbf.append(attr.getNodeName() + "=\"" + attr.getNodeValue()
       + "\"");
    }
   }
   sbf.append(">");
   // System.out.print(sbf.toString());
  }
  if (node.getNodeType() == Node.TEXT_NODE) { // 文本類型,輸出文本
   sbf.append(((Text) node).getWholeText());
   // System.out.print(((Text) node).getWholeText());
  }

  NodeList allNodes = node.getChildNodes();// 擷取所要遍曆節點的子節點
  int size = allNodes.getLength();
  if (size > 0) {
   for (int j = 0; j < size; j++) {
    Node childNode = allNodes.item(j);
    nodeTranserse(childNode, sbf);
    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
     // 每遍曆完一個標籤,輸出結束標籤
     sbf.append("</" + childNode.getNodeName() + ">");
     // System.out.print("</" + childNode.getNodeName() + ">");
    }
   }
  }
 }

 public static void main(String[] args) throws IOException,
   ParserConfigurationException, SAXException, InterruptedException {
  // 項目根目錄
  String projectPath = "E:\\workspace\\Bless\\";
  // 檢測問題件
  String resultPath = projectPath + "result.xml";
  // 檢測檔案比對未使用結果
  String checkPath = projectPath + "check.xml";
  // 指定刪除無用節點values目錄
  String clearPath = projectPath + "res\\values\\";

  // lint 檢測 並將結果儲存在項目根目錄result.xml
  doDocCheck(projectPath, resultPath);

  // 刪除無憂drawable layout anim menu
  clearResources(projectPath, resultPath);

  // 檢測value 目錄項未使用的clor string string-array等,並儲存在項目根目錄check.xml
  checkResource(resultPath, checkPath);

  // 刪除values 目錄項無用的節點
  prepairClear(clearPath, checkPath);
 }
}

 

 


大家湊活看吧。

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.