1. 程式人生 > >Json壓縮工具

Json壓縮工具

null list集合 param exceptio oid 遞歸 con init ole

一般的json文件擁有很多的空格和註釋,雖然讀起來比較方便,但是在運行的時候是要占一些內存的。

於是json壓縮工具就應運而生了,這個工具是用java做的,原理是:

1:在Eclipse中導出一個可運行的jar文件

2:用python運行這個jar文件,並向這個jar文件的運行程序傳一些main方法的參數(一般只傳路徑就可以了)

//bat文件的代碼如下:
set assetsAPath="..\javaOutput\assets\uijson"    原json文件路徑
set assetsBPath="..\javaOutput\assets\uijson\\"  壓縮後的json文件路徑
set targetJar="JSONMinify.jar" 
cd ./lang
java -jar lib/JSONMinify.jar
cd ..
cd ./tools
java -jar %targetJar% resVersion=%resVersion%  assetsAPath=%assetsAPath% assetsBPath=%assetsBPath% 

pause

  

//java代碼如下
package com.pack;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.zhaohe.download.ResourceDownloader;

public class JSONMinify {

	static ArrayList<String> fileName;

	public static void main(String[] args) throws Exception {
		initArgs(args);
		String fileData1 = assetsAPath;
		String fileDatas2 = assetsBPath;

		fileName = new ArrayList<String>();
		File folder = new File(fileDatas2);
		List<String> filesPath = getAllFile(fileData1, false);

		System.err.println(getAllFile(fileData1, false).size());

		System.err.println(fileData1);

		for (int i = 0; i < getAllFile(fileData1, false).size(); i++) {
			System.err.println(filesPath.get(i));

			File file = new File(filesPath.get(i));// 需要讀取的文件
			File file1 = new File(fileDatas2, fileName.get(i));// 需要寫進去的文件
			String fileContext = txt2String(file);// 文件內容
			file.delete();
			if (!file1.exists()) {
				file.createNewFile();
			}
			BufferedWriter out = new BufferedWriter(new FileWriter(fileDatas2 + fileName.get(i)));

			out.write(minify(fileContext));
			out.close();

		}
	}

	private static final String manifestFileName = "assetsManifest.txt";
	private static final String remoteVersionFile = "assetsVersion.txt";
	private static final String lcoalVersionFile = "localAssetsVersion.txt";

	private static String version = "1.0.2";
	private static String assetsAPath = "..\\android\\assets\\uiname\\";
	private static String assetsBPath = "..\\android\\assets\\uijson\\";
	private static String rootFolder = ".\\packages";
	private static String cdnUrl = "http://www.mathmt.com";
	private static String serverID = "12";
	private static String resVersion = String.valueOf(ResourceDownloader.RES_TYPE_CURRENT);

	public static void initArgs(String args[]) {
		if (args != null) {
			for (String arg : args) {
				String[] keyValue = arg.split("=");
				final String key = keyValue[0];
				final String value = keyValue[1];
				if ("targetVersion".equals(key)) {
					version = value;
				} else if ("assetsAPath".equals(key)) {
					assetsAPath = value;
				} else if ("assetsBPath".equals(key)) {
					assetsBPath = value;
				} else if ("cdnUrl".equals(key)) {
					cdnUrl = value;
				} else if ("rootFolder".equals(key)) {
					rootFolder = value;
				} else if ("serverID".equals(key)) {
					serverID = value;
				} else if ("resVersion".equals(key)) {
					resVersion = value;
				} else {
					System.out.println("Unknown key:" + key);
				}
			}
		}
	}

	public static boolean deleteDir(String path) {
		File file = new File(path);
		if (!file.exists()) {// 判斷是否待刪除目錄是否存在
			return false;
		}

		String[] content = file.list();// 取得當前目錄下所有文件和文件夾
		for (String name : content) {
			File temp = new File(path, name);
			if (temp.isDirectory()) {// 判斷是否是目錄
				deleteDir(temp.getAbsolutePath());// 遞歸調用,刪除目錄裏的內容
				temp.delete();// 刪除空目錄
			} else {
				if (!temp.delete()) {// 直接刪除文件
					temp.delete();
					System.err.println("Failed to delete " + name);
				}
			}
		}
		return true;
	}

	/*
	 * 讀取txt文件的內容
	 * 
	 * @param file 想要讀取的文件對象
	 * 
	 * @return 返回文件內容
	 */
	public static String txt2String(File file) {
		StringBuilder result = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));// 構造一個BufferedReader類來讀取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法,一次讀一行
				result.append(System.lineSeparator() + s);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * 以行為單位讀取文件,常用於讀面向行的格式化文件
	 */
	public static void readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行為單位讀取文件內容,一次讀一整行:");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次讀入一行,直到讀入null為文件結束
			while ((tempString = reader.readLine()) != null) {
				// 顯示行號
				System.out.println("line " + line + ": " + tempString);

				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	/**
	 * 獲取路徑下的所有文件/文件夾
	 * 
	 * @param directoryPath
	 *            需要遍歷的文件夾路徑
	 * @param isAddDirectory
	 *            是否將子文件夾的路徑也添加到list集合中
	 * @return
	 */
	public static List<String> getAllFile(String directoryPath, boolean isAddDirectory) {
		List<String> list = new ArrayList<String>();
		File baseFile = new File(directoryPath);
		if (baseFile.isFile() || !baseFile.exists()) {
			return list;
		}
		File[] files = baseFile.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				if (isAddDirectory) {
					list.add(file.getAbsolutePath());
				}
				list.addAll(getAllFile(file.getAbsolutePath(), isAddDirectory));
			} else {

				list.add(file.getAbsolutePath());
				fileName.add(file.getName());
			}
		}
		return list;
	}

	public static String minify(String jsonString) {
		boolean in_string = false;
		boolean in_multiline_comment = false;
		boolean in_singleline_comment = false;
		char string_opener = ‘x‘;

		StringBuilder out = new StringBuilder();
		for (int i = 0; i < jsonString.length(); i++) {
			char c = jsonString.charAt(i);
			String cc = jsonString.substring(i, Math.min(i + 2, jsonString.length()));
			if (in_string) {
				if (c == string_opener) {
					in_string = false;
					out.append(c);
				} else if (c == ‘\\‘) {
					out.append(cc);
					++i;
				} else
					out.append(c);
			} else if (in_singleline_comment) {
				if (c == ‘\r‘ || c == ‘\n‘)
					in_singleline_comment = false;
			} else if (in_multiline_comment) {
				if (cc.equals("*/")) {
					in_multiline_comment = false;
					++i;
				}
			} else {
				if (cc.equals("/*")) {
					in_multiline_comment = true;
					++i;
				} else if (cc.equals("//")) {
					in_singleline_comment = true;
					++i;
				} else if (c == ‘"‘ || c == ‘\‘‘) {
					in_string = true;
					string_opener = c;
					out.append(c);
				} else if (!Character.isWhitespace(c))
					out.append(c);
			}
		}
		return out.toString();
	}
}

  

Json壓縮工具