public static void main(String[] args) throws IOException { if (args.length == 2) { File file = new File(args[1]); if (file.exists()) { file.delete(); } Map<String, Map<String, Long>> invertedIndex = getInvertedIndex(args[0]); invertedIndex .entrySet() .forEach( entry -> { String line = serializeIndexEntry(entry); FileUtils.appendToFile(args[1], line); }); FileUtils.appendToFile(args[1], DOC_LENGTH_SEPARATOR); Map<String, Long> documentAndLength = getDocumentAndLength(args[0]); documentAndLength .entrySet() .forEach( entry -> { String doc = entry.getKey(); Long length = entry.getValue(); FileUtils.appendToFile(args[1], String.format("%s=%d", doc, length)); }); } else { System.out.println("Usage: input_file output_file"); } }
/** * 批量修改图片sel文件名,复制的方式拷贝到同级目录下的sel文件夹中 <br> * 修改成功后请再使用batchCreateSelFiles方法生成对应的sel.xml文件 * * @param normalPath normal普通状态图片的文件夹 * @param specialPath 特殊状态(pressed按下/checked选中)图片的文件夹 * @param pre 需要添加的前缀 * @param end 特殊状态(pressed按下/checked选中)后缀名 */ public static void batchRenameSelFiles( String normalPath, String specialPath, String pre, String end) { String savePath = normalPath.substring(0, normalPath.lastIndexOf("\\")); File saveDir = new File(savePath, "sel"); if (!saveDir.exists()) { saveDir.mkdirs(); } List<File> files = FileUtils.getAllFiles(normalPath); for (File file : files) { String fileName = pre + "_" + file.getName(); fileName = fileName.replace(" ", "_").toLowerCase(Locale.CHINESE); File nFile = new File(saveDir, fileName); // file.renameTo(nFile); // rename 直接移动文件,我们希望是复制并重命名 FileUtils.copyFileByChannel(file, nFile); } List<File> filePresses = FileUtils.getAllFiles(specialPath); for (File file : filePresses) { String[] nameMap = FileUtils.getNameMap(file); String fileName = pre + "_" + nameMap[0] + "_" + end + nameMap[1]; fileName = fileName.replace(" ", "_").toLowerCase(Locale.CHINESE); File nFile = new File(saveDir, fileName); // file.renameTo(nFile); // rename 直接移动文件,我们希望是复制并重命名 FileUtils.copyFileByChannel(file, nFile); } }
/** * Save file into specified directory. * * @param file Origin upload file. * @return fileName */ public static String saveItemImage(File file) { String path = FileUtils.getApplicationPath("data", "item", "images"); String ext = FileUtils.getFileExtension(file.getName()); String fileName = UUID.randomUUID().toString() + "." + ext; Images.resize(file, new File(path + fileName), 800, 800, true); return fileName; }
public static void deleteImage(String fileName) { String imagePath = FileUtils.getApplicationPath("data", "item", "images"); String thumbPath = FileUtils.getApplicationPath("data", "item", "thumbnails"); File image = new File(imagePath + fileName); File thumb = new File(thumbPath + fileName); if (image.exists()) image.delete(); if (thumb.exists()) thumb.delete(); }
/** * 批量生成sel的xml文件 <br> * 比如图片名字是ic_img.png和按下的ic_img_pressed.png,那么最终生成的就是封装好的ic_img_sel.xml * * @param path 包含全部图片的文件路径 * @param end 特殊状态(pressed按下/checked选中)后缀名 */ public static void batchCreateSelFiles(String path, String end) { List<File> files = FileUtils.getAllFiles(path); for (File file : files) { String fileName = FileUtils.getName(file); // 用normal状态的图片名生成对应的_sel.xml文件 if (!fileName.endsWith(end)) { Document doc = createSelector(fileName, fileName + "_" + end, end); // fileName + "_" + end File nFile = new File(path, fileName + "_sel.xml"); XmlUtil.write2xml(nFile, doc); } } }
/** * 删除旧的缩略图,生成新的缩略图 * * @param fileName * @param oldName */ public static void saveThumbnail(String fileName, String oldName) { String imagePath = FileUtils.getApplicationPath("data", "item", "images"); String thumbPath = FileUtils.getApplicationPath("data", "item", "thumbnails"); File old = new File(thumbPath + oldName); if (old.exists()) { old.delete(); } File image = new File(imagePath + fileName); File thumb = new File(thumbPath + fileName); if (image.exists()) { Images.resize(image, thumb, 200, 150, true); } }
public static String saveItemBlobImage(String blob) { String path = FileUtils.getApplicationPath("data", "item", "images"); String ext = FileUtils.getBlobExtension(blob); String fileName = UUID.randomUUID().toString() + "." + ext; byte[] bytes = Codec.decodeBASE64(blob.substring(blob.indexOf(",") + 1)); InputStream is = new ByteArrayInputStream(bytes); try { BufferedImage img = ImageIO.read(is); ImageIO.write(img, ext, new File(path + fileName)); } catch (IOException e) { e.printStackTrace(); } return fileName; }
/** * 自动遍历xml中所有带id的控件,在adapter文件中生成最基本的代码 * * @param layoutXml item布局文件的绝对路径,如xxx/res/layout/item.xml * @param adapterFile Adapter类文件名,如xxx/src/.../MyAdapter.java * @param include 是否将include引用的布局中内容也获取到 */ public static void autoCreateAdapter(String layoutXml, String adapterFile, boolean include) { idNamingBeans.clear(); parseElementFromXml(layoutXml, include); String adapterContent = createAdapterContent(layoutXml); // 读取java文件的字符串 File javaFile = new File(adapterFile); String fileContent = FileUtils.readToString(javaFile); // 将生成的内容写入至java类文件内的起始端 fileContent = fileContent.replaceFirst("\\{", "\\{\n" + adapterContent); // 写入回文件 FileUtils.writeString2File(fileContent, javaFile); }
private boolean executeCantico(int numCantico) { String[] arquivos = FileUtils.fileNamesOnFolder(CANTICOS_FOLDER); String fileNameExpected = CANTICOS_FILEPREFIX + String.format("%03d", numCantico) + ".mp3"; boolean foundFile = false; for (String arquivo : arquivos) { if (arquivo.equals(fileNameExpected)) { try { if (audioThread != null && audioThread.isAlive()) { audioPlayer.stop(); audioThread.interrupt(); } audioPlayer = new AudioPlayer(new File(CANTICOS_FOLDER + "\\" + arquivo)); audioThread = new Thread(audioPlayer); audioThread.start(); foundFile = true; print("executing " + fileNameExpected); break; } catch (Exception e) { e.printStackTrace(); } } } return foundFile; }
/** * 自动遍历xml中所有带id的控件,在activity文件中设置对应变量,变量名为id名 * * @param layoutXml 布局文件的绝对路径,如xxx/res/layout/main.xml * @param activityFile Activity类文件名,如xxx/src/.../MainActivity.java * @param include 是否将include引用的布局中内容也获取到 */ public static void autoCreateActivity(String layoutXml, String activityFile, boolean include) { // 获取layout中控件信息,信息会保存至idNamingBeans集合中 idNamingBeans.clear(); parseElementFromXml(layoutXml, include); // 解析idNamingBeans集合中的信息,生成页面文本信息 String activityContent = createActivityContent(); // 获取activity文件 File javaFile = new File(activityFile); // 读取java文件的字符串 String fileContent = FileUtils.readToString(javaFile); // 将生成的内容写入至java类文件内的起始端 fileContent = fileContent.replaceFirst("\\{", "\\{" + activityContent); FileUtils.writeString2File(fileContent, javaFile); }
/** * 删除无用的src文件 * * @param rootPath 根目录的绝对路径 */ public static void delNoUseSrcFile(String rootPath) { List<File> files = FileUtils.getAllFiles(rootPath); out: for (File file : files) { String name = file.getName(); // 只需要删除src包下的文件 if (!file.getPath().contains("\\src\\")) { continue; } for (File compareFile : files) { String compareName = compareFile.getName(); if (name.equals(compareName)) { // 自己跟自己不匹配 continue; } // 只需要对比src包和layout包下的文件 if (!compareFile.getPath().contains("\\src\\") && !compareFile.getPath().contains("\\layout")) { continue; } if (!compareFile.exists()) { continue; } // 如果对比文件的本文内容中包含文件名,则视为有使用 String fileContent = FileUtils.readToString(compareFile); if (fileContent.contains(FileUtils.getName(file))) { continue out; } } // 删除没使用过的文件 String absname = file.getAbsoluteFile().getName(); boolean delete = file.delete(); System.out.println(absname + " ... delete=" + delete); } }
public static void main(String[] args) { // Read property file PropertyFileReader reader = new PropertyFileReader("sensors.properties"); // m2x settings String deviceID = reader.getPropertyValue(reader.DEVICE_ID); String luminosityStream = reader.getPropertyValue(reader.LUMINOSITY_STREAM); String m2xKey = reader.getPropertyValue(reader.M2X_KEY); boolean displayLum = reader.getPropertyValue(reader.TSL2561_DISPLAY_LUM_IN_CONSOLE).equals("true"); String measurementInterval = reader.getPropertyValue(reader.TSL2561_MEASUREMENT_INTERVAL_SECONDS); boolean readLum = reader.getPropertyValue(reader.TSL2561_READ_LUM).equals("true"); boolean sendLumToM2X = reader.getPropertyValue(reader.TSL2561_SEND_LUM_TO_M2X).equals("true"); boolean writeLumToTfile = reader.getPropertyValue(reader.TSL2561_WRITE_LUM_TO_FILE).equals("true"); String lumFile = reader.getPropertyValue(reader.TSL2561_LUM_FILE); int measurementIntervalSec = Integer.parseInt(measurementInterval); try { while (true) { TSL2561 device = new TSL2561(); device.initialize(); DecimalFormat df = new DecimalFormat(".##"); if (readLum) { double lux = device.getLux(); String luxStr = df.format(lux); if (displayLum) { System.out.println(lux); } if (writeLumToTfile) { FileUtils.writeSrtToFile(luxStr, lumFile, false); } if (sendLumToM2X) { M2X.sendValueToStream(luxStr, deviceID, luminosityStream, m2xKey); } } Thread.sleep(measurementIntervalSec * 1000); } } catch (Exception e) { System.out.println(e); e.printStackTrace(); } }
public static void relaceLayoutViewNames( String proPath, List<String> tarList, String replacement) { List<File> allFiles = FileUtils.getAllFiles(proPath); for (File file : allFiles) { // 如果是xml文件,且在layout..目录下,则视为布局文件 if (file.getName().endsWith(".xml") && file.getParentFile().getName().startsWith("layout")) { Document document = XmlUtil.read(file); boolean hasReplace = XmlUtil.replaceElementName(document, tarList, replacement); if (hasReplace) { XmlUtil.write2xml(file, document); } } } }
/** * 自动遍历xml中所有带id的控件,在activity文件中设置对应变量,变量名为id名<br> * <br> * 使用前需要将xml文件内容复制到本项目里的Android文件夹下的layout.xml文件中<br> * 运行该方法后,根据布局文件生成的相关代码会在Android文件夹下Activity.java中查看,可以复制到自己项目里使用 */ public static void autoCreateActivity() { // 获取layout中控件信息,信息会保存至idNamingBeans集合中 idNamingBeans.clear(); parseElementFromXml("Android" + File.separator + "layout.xml", false); // 解析idNamingBeans集合中的信息,生成页面文本信息 String activityContent = createActivityContent(); // 获取activity文件 File javaFile = new File("Android" + File.separator + "Activity.java"); // 将生成的内容写入至java类文件中 FileUtils.writeString2File(activityContent, javaFile, "utf-8"); }
/** * 自动遍历xml中所有带id的控件,在adapter文件中生成最基本的代码<br> * <br> * 使用前需要将xml文件内容复制到本项目里的Android文件夹下的item.xml文件中<br> * 运行该方法后,根据布局文件生成的相关代码会在Android文件夹下Adapter.java中查看,可以复制到自己项目里使用 */ public static void autoCreateRecyclerAdapter() { String layoutXml = "Android" + File.separator + "item_recyclerview.xml"; // 获取layout中控件信息,信息会保存至idNamingBeans集合中 idNamingBeans.clear(); parseElementFromXml(layoutXml, false); // 解析idNamingBeans集合中的信息,生成适配器文本信息 String adapterContent = createRecyclerAdapterContent(layoutXml); // 获取adapter文件 File javaFile = new File("Android" + File.separator + "RecyclerAdapter.java"); // 将生成的内容写入至java类文件中 FileUtils.writeString2File(adapterContent, javaFile); }
public static List<CaoMain> getMainUrl() { // String response = HttpUtils.getString(mainUrl); String response = FileUtils.readToString( new File("temp" + File.separator + "reptile" + File.separator + "bcgm_main.txt"), "UTF-8"); String type = null; List<CaoMain> caos = new ArrayList<CaoMain>(); Document parse = Jsoup.parse(response); Elements allElements = parse.getAllElements(); for (int i = 0; i < allElements.size(); i++) { Element element = allElements.get(i); // <span class="mw-headline" // id=".E8.8D.89.E9.83.A8">草部</span> String attrClass = element.attr("class"); if ("mw-headline".equals(attrClass + "")) { type = element.text(); continue; } // <a // href="/w/%E6%9C%AC%E8%8D%89%E7%BA%B2%E7%9B%AE/%E7%94%98%E8%8D%89" // title="本草纲目/甘草">甘草</a> String title = element.attr("title"); String href = element.attr("href"); if (type != null && href != null && title != null && title.startsWith("本草纲目/")) { CaoMain cao = new CaoMain(); cao.setType(type); cao.setName(element.text()); cao.setHref(DOMAIN_URL + href); caos.add(cao); } } return caos; }
public Mensagem clientSendMessage(Mensagem msg) { String[] args = msg.getMensagem().split(" "); String retMsg = "opcao não encontrada"; if (args.length > 0) { if (args.length >= 2) { if (args[0].equals("cantico")) { retMsg = "executando cantico " + args[1] + ", tema 'jeová é o refugio'"; } } if (args[0].equals("listar")) { String[] arquivos = FileUtils.fileNamesOnFolder("E:\\musicas\\canticos"); StringBuilder bulder = new StringBuilder("todos os canticos \n#listaCanticos"); for (String string : arquivos) { bulder.append("\n" + string); } bulder.append("\n" + "#listaCanticos"); retMsg = bulder.toString(); } if (args[0].equals("tocar_cantico")) { if (args.length >= 2) { int numCantico = 0; try { numCantico = Integer.parseInt(args[1]); if (numCantico > 0 && executeCantico(numCantico)) { retMsg = "executing cantico " + numCantico; } else { retMsg = "não foi possivel executar o cantico"; } } catch (NumberFormatException e) { retMsg = "Número do Cantico[parametro 2] invalido"; } } else { retMsg = "Segundo parametro não informado"; } } } return new Mensagem(msg.getCliente(), msg.getServidor(), retMsg, Origem.Servidor); }
public CustomImageCache() { int maxSize = (int) Runtime.getRuntime().maxMemory() / 8; mMemoryCache = new LruCache<String, Bitmap>(maxSize) { @Override protected int sizeOf(String key, Bitmap value) { // 这个方法一定要重写,不然缓存没有效果 return value.getHeight() * value.getRowBytes(); } }; try { // 获取图片缓存路径 File cacheDir = FileUtils.getDiskCacheDir("thumb"); if (!cacheDir.exists()) { cacheDir.mkdirs(); } // 创建DiskLruCache实例,初始化缓存数据 mDiskLruCache = DiskLruCache.open(cacheDir, CommonUtils.getAppVersion(), 1, DISK_CACHE_MAX_SIZE); } catch (IOException e) { e.printStackTrace(); } }
/** * get document and their corresponding length * * @param stemmedFile String stemmed file path * @return Map of Document -> Length * @throws IOException */ private static Map<String, Long> getDocumentAndLength(String stemmedFile) throws IOException { HashMap<String, Long> documentLength = new HashMap<>(); Stream<String> stemmed = FileUtils.readFiles(stemmedFile); Iterator<String> reader = stemmed.iterator(); String lastDocId = null; while (reader.hasNext()) { String line = reader.next(); if (isDocument(line)) { lastDocId = line.replace('#', ' ').trim(); documentLength.put(lastDocId, 0L); } else { long length = Arrays.stream(line.split(SEPARATOR_SPACE)).filter(Indexer::isNotNumber).count(); if (documentLength.containsKey(lastDocId)) { documentLength.put(lastDocId, documentLength.get(lastDocId) + length); } else { documentLength.put(lastDocId, length); } } } return documentLength; }
/** * build inverted index from stemmed documents collection * * @param inputFile String input file * @return Map of {Term, List of Document and Frequency} * @throws IOException when input file is not accessible */ private static Map<String, Map<String, Long>> getInvertedIndex(String inputFile) throws IOException { Map<String, Map<String, Long>> cache = new TreeMap<>(); Iterator<String> reader = FileUtils.readFiles(inputFile).iterator(); String lastDocId = null; while (reader.hasNext()) { String line = reader.next(); if (isDocument(line)) { lastDocId = line.replace('#', ' ').trim(); } else if (lastDocId != null) { List<String> terms = getAllTerms(line); for (String term : terms) { // if term already present in index Map<String, Long> index; if (cache.containsKey(term)) { index = cache.get(term); if (index.containsKey(lastDocId)) { index.put(lastDocId, index.get(lastDocId) + 1L); } else { index.put(lastDocId, 1L); } } else { index = new TreeMap<>(); index.put(lastDocId, 1L); } cache.put(term, index); } } } return cache; }
/** 生成activity对应的测试文件内容(针对已经写好的页面代码生成) */ public static String createActivityContent4EspressoTest(String projectPath, String activityPath) { StringBuilder sb = new StringBuilder(); sb.append("\n\n"); File activityFile = new File(projectPath + activityPath); // 页面名 String activityName = FileUtils.getName(activityFile); // 页面内容 String activityContent = FileUtils.readToString(activityFile, "UTF-8"); // 布局内容元素 List<IdNamingBean> layoutElements; // setContentView(R.layout.activity_login); String setContentViewRegex = "setContentView\\(R.layout.([\\w_]+)\\);"; Pattern setContentViewPattern = Pattern.compile(setContentViewRegex); Matcher setContentViewMatcher = setContentViewPattern.matcher(activityContent); if (setContentViewMatcher.find()) { // projectPath = D:\PlayFun\HaveFun // layoutPath = projectPath + \app\src\main\res\layout String layoutPath = projectPath + "\\app\\src\\main\\res\\layout\\" + setContentViewMatcher.group(1) + ".xml"; parseElementFromXml(layoutPath, true); layoutElements = idNamingBeans; } else { throw new RuntimeException("页面必须要setContentView绑定布局"); } // 类名: 页面名+Test String className = activityName + "Test"; // @RunWith(AndroidJUnit4.class) // public class RegistActivityTest { // // @Rule // public ActivityTestRule<RegistActivity> mActivityRule = new // ActivityTestRule<>(RegistActivity.class, true, false); sb.append(StringUtils.formatSingleLine(0, "@RunWith(AndroidJUnit4.class)")); sb.append(StringUtils.formatSingleLine(0, "public class " + className + " {")); sb.append("\n"); sb.append(StringUtils.formatSingleLine(1, "@Rule")); sb.append( StringUtils.formatSingleLine( 1, "public ActivityTestRule<" + activityName + "> mActivityRule = new ActivityTestRule<>(" + activityName + ".class, true, false);")); sb.append("\n"); // @Test // public void test() { sb.append(StringUtils.formatSingleLine(1, "@Test")); sb.append(StringUtils.formatSingleLine(1, "public void test() {")); // 页面初始化 sb.append(StringUtils.formatSingleLine(2, "Intent intent = new Intent();")); // 判断页面初始化时是否有getExtra,如果有需要在测试代码中putExtra // userId = getIntent().getLongExtra("userId", 0); String getExtraRegex = ".get([\\w]+)Extra\\(\"([\\w_]+)\""; Pattern getExtraPattern = Pattern.compile(getExtraRegex); Matcher getExtraMatcher = getExtraPattern.matcher(activityContent); if (getExtraMatcher.find()) { // Intent intent = new Intent(); // intent.putExtra("userId", 1016l); // mActivityRule.launchActivity(intent); sb.append(StringUtils.formatSingleLine(2, "// 待测试页面需要Extra数据如下")); String type = getExtraMatcher.group(1); String key = getExtraMatcher.group(2); sb.append( StringUtils.formatSingleLine(2, "intent.putExtra(\"" + key + "\", 添加" + type + "类型的值);")); } sb.append(StringUtils.formatSingleLine(2, "mActivityRule.launchActivity(intent);")); sb.append("\n"); // 用onView定位控件,并执行动作 // onView(withId(R.id.et_username)).perform(typeText("boredream"), closeSoftKeyboard()); for (IdNamingBean bean : layoutElements) { // 控件名 String viewName = bean.getViewName(); // 不同控件对应的操作 String perform = ""; // 一般自定义控件都会在名字里表明自己的类型,因此使用contains判断 if (viewName.contains("EditText")) { // EditText对应输入 perform = ".perform(typeText(输入测试内容), closeSoftKeyboard())"; } else if (viewName.contains("Button") || viewName.contains("CheckBox")) { // Button/RadioButton/CheckBox对应点击 perform = ".perform(click())"; } else { // 无法判断的类型,不添加动作 } sb.append( StringUtils.formatSingleLine( 2, "onView(withId(R.id." + bean.getIdName() + "))" + perform + ";")); } // 最后验证部分,留给开发者自己根据业务处理,添加部分注释引导 // TODO 复制上面的onView部分定位控件,然后根据需要编写期望的check结果 // 示例: 比如需要验证dialog/toast是否显示可以如下(如果验证页面上控件则不需要.inRoot部分) // onView(withText("登录")) // // .inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView())))) // .check(matches(isDisplayed())); sb.append("\n"); sb.append(StringUtils.formatSingleLine(2, "// TODO 复制上面的onView部分定位控件,然后根据需要编写期望的check结果")); sb.append( StringUtils.formatSingleLine( 2, "// 示例: 比如需要验证dialog/toast是否显示可以如下(如果验证页面上控件则不需要.inRoot部分)")); sb.append(StringUtils.formatSingleLine(2, "// onView(withText(\"请输入密码\"))")); sb.append( StringUtils.formatSingleLine( 2, "// .inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView()))))")); sb.append(StringUtils.formatSingleLine(2, "// .check(matches(isDisplayed()));")); sb.append("\n"); sb.append(StringUtils.formatSingleLine(1, "}")); sb.append(StringUtils.formatSingleLine(0, "}")); return sb.toString(); }
public static ArrayList<RequestInfo> parseApiDoc(String path) { File file = new File(path); String response = FileUtils.readToString(file, "UTF-8"); Document parse = Jsoup.parse(response); // 接口类型总称 api-Search String mainName = parse.getElementsByTag("section").get(0).attr("id"); // System.out.println("-> type = " + mainName); // System.out.println(); ArrayList<RequestInfo> requestInfos = new ArrayList<RequestInfo>(); // 全部类型接口 for (Element e : parse.getAllElements()) { String attrId = e.attr("id"); // div的标签,且id名前缀为mainName // 为类型下单个接口 api-Search-PostSearchCompany if (e.tagName().equals("div") && attrId.startsWith(mainName)) { RequestInfo requestInfo = new RequestInfo(); // System.out.println("---> name = " + attrId); requestInfo.setName(attrId); // method post/get String method = e.getElementsByTag("pre").get(0).attr("data-type"); // System.out.println("-----> method = " + method); requestInfo.setMethod(method); // url String url = e.getElementsByAttributeValue("class", "pln").get(0).text(); // System.out.println("-----> url = " + url); requestInfo.setUrl(url); // des String des = e.getElementsByAttributeValue("class", "pull-left").get(0).text(); // System.out.println("-----> des = " + des); requestInfo.setDes(des); // post params Element ePostParams = e.getElementsByTag("table").get(0); ArrayList<RequestParam> params = new ArrayList<RequestParam>(); for (Element ePostParam : ePostParams.getElementsByTag("tr")) { // param 字段 Elements eColumn = ePostParam.getElementsByTag("td"); if (eColumn.size() == 0) { continue; } // 标签"选项" // String label = ePostParam.getElementsByAttributeValue("class", "label // label-optional") // .get(0).text(); String label = "选项"; // 第一个字段为参数名 String paramName = eColumn.get(0).text(); // 去除标签 paramName = paramName.replace(label, "").trim(); // 第二个字段为参数类型 // 可能类型为 String Number Float String paramType = eColumn.get(1).text(); // 第三个字段为参数描述 String paramDes = eColumn.get(2).text(); // System.out.println("-----> param = " + paramName + " ... " // + paramType + " ... " + paramDes); RequestParam param = new RequestParam(paramName, paramType, paramDes); params.add(param); } requestInfo.setParams(params); requestInfos.add(requestInfo); // System.out.println(); } } return requestInfos; }
/** 生成adapter文件内容 */ private static String createAdapterContent(String layoutXml) { StringBuilder sbAdapterInfo = new StringBuilder(); sbAdapterInfo.append("\n"); // 成员变量,只设置最基本的集合类和context sbAdapterInfo.append(StringUtils.formatSingleLine(1, "private Context context;")); sbAdapterInfo.append( StringUtils.formatSingleLine(1, "// TODO change the MyItem class to your data bean class")); sbAdapterInfo.append(StringUtils.formatSingleLine(1, "private List<MyItem> datas;")); sbAdapterInfo.append("\n"); // 根据成员变量创建的构造函数 sbAdapterInfo.append( StringUtils.formatSingleLine(1, "public MyAdapter(Context context, List<MyItem> datas) {")); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "this.context = context;")); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "this.datas = datas;")); sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}")); sbAdapterInfo.append("\n"); // 重写getCount方法 sbAdapterInfo.append(StringUtils.formatSingleLine(1, "@Override")); sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public int getItemCount() {")); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "return datas.size();")); sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}")); sbAdapterInfo.append("\n"); // ViewHolder class的申明处理 sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public static class ViewHolder{")); for (IdNamingBean bean : idNamingBeans) { // public TextView item_tv; sbAdapterInfo .append("\t\t") .append("public ") .append(bean.getViewName()) .append(" ") .append(bean.getIdName()) .append(";\n"); } sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}")); // 重写getView方法,并进行优化处理 sbAdapterInfo.append(StringUtils.formatSingleLine(1, "@Override")); sbAdapterInfo.append( StringUtils.formatSingleLine( 1, "public View getView(int position, View convertView, ViewGroup parent) {")); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "ViewHolder holder;")); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "if(convertView == null) {")); sbAdapterInfo.append(StringUtils.formatSingleLine(3, "holder = new ViewHolder();")); sbAdapterInfo.append( StringUtils.formatSingleLine( 3, "convertView = View.inflate(context, R.layout." + FileUtils.getName(layoutXml) + ", null);")); // getView中viewholder的变量赋值处理 // 根据view名-id名的实体类,依次生成控件对应的holder变量,变量名取id名称赋值 for (IdNamingBean bean : idNamingBeans) { // holder.item_tv = (TextView) convertView.findViewById(R.id.item_tv); sbAdapterInfo .append("\t\t\t") .append("holder.") .append(bean.getIdName()) .append(" = (") .append(bean.getViewName()) .append(") ") .append("convertView.findViewById(R.id.") .append(bean.getIdName()) .append(");\n"); } sbAdapterInfo.append(StringUtils.formatSingleLine(3, "convertView.setTag(holder);")); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "} else {")); sbAdapterInfo.append( StringUtils.formatSingleLine(3, "holder = (ViewHolder) convertView.getTag();")); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "}")); sbAdapterInfo.append("\n"); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "// TODO set data")); sbAdapterInfo.append("\n"); sbAdapterInfo.append(StringUtils.formatSingleLine(2, "return convertView;")); sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}")); sbAdapterInfo.append("\n"); sbAdapterInfo.append("\n"); return sbAdapterInfo.toString(); }
/** * 将参数值抽取到values文件夹下 * * <p>如textColor="#ff00aa",将#ff00aa这样的具体值替换为@color/colorname <br> * 并在color.xml文件内创建一个对应颜色item * * @param proPath 项目绝对路径 * @param valuesXml values文件名称,如strings.xml dimens.xml等 * @param type 抽取内容的前缀,如@color/,则type参数就输入"color" * @param itemName values文件内item的名称 * @param itemAttrName values文件内item的参数,一般都是name * @param itemAttrValue values文件内item的参数值,也是抽取值后替换的名称 * @param itemValue values文件内item的值,即替换后的值 * @param values 被替换的内容,支持模糊替换,只要匹配集合里中其中一个就会被抽取替换,最终抽取成一个值itemValue * @param matchAttr 匹配参数名,即只会替换该参数名对应的值 */ @SuppressWarnings("unchecked") public static void extract2valuesByJsoup( String proPath, String valuesXml, String type, String itemName, String itemAttrName, String itemAttrValue, String itemValue, List<String> values, String matchAttr) { List<File> files = FileUtils.getAllFiles(new File(proPath)); String valuesPath = proPath + "/res/values/" + valuesXml; File valuesFile = new File(valuesPath); if (!valuesFile.exists()) { System.out.println("文件不存在,请确定文件[" + valuesXml + "]位于/res/values/文件夹下,且文件名称正确"); return; } int extractFileCount = 0; for (File file : files) { if (!file.getName().endsWith(".xml")) { continue; } if (file.getName().equals(valuesXml)) { continue; } Document tarDoc = XmlUtil.read(file); // 是否有替换操作 boolean isReplace = XmlUtil.replaceAttrValue(tarDoc, values, "@" + type + "/" + itemAttrValue, matchAttr); if (!isReplace) { continue; } XmlUtil.write2xml(file, tarDoc); Document valuesDoc = XmlUtil.read(valuesFile); Element rootElement = valuesDoc.getRootElement(); List<Element> elements = rootElement.elements(); // 是否在values/xx.xml对应文件下下已有某个抽取过的值 boolean hasInValues = false; for (Element element : elements) { String attrValue = element.attributeValue(itemAttrName); if (attrValue.equals(itemAttrValue)) { hasInValues = true; break; } } if (!hasInValues) { Element element = rootElement.addElement(itemName); element.addAttribute(itemAttrName, itemAttrValue); element.setText(itemValue); XmlUtil.write2xml(valuesFile, valuesDoc); } extractFileCount++; } System.out.println( "将" + values + "抽取为[" + valuesXml + "]文件下的[" + itemAttrValue + "=" + itemValue + "]"); System.out.println("共抽取了" + extractFileCount + "个文件下的内容"); System.out.println("-------------------------"); }