Java tutorial
//package com.java2s; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class Main { public static boolean encodeLZW(String inText, int dictSize, int[] encodedData) { int[] returnData = { 0 }; try { encodedData = new int[inText.length()]; int outCount = 0; HashMap<Integer, String> dict = newDictLZW(inText); String teststring = ""; for (int i = 0; i < inText.length() - 1; i++) { teststring = String.valueOf(inText.charAt(i)); String prevstring = teststring; int j = 0; // System.out.println("teststring = " + teststring + // "; prevstring= " + prevstring + "; i= " + i); while (dict.containsValue(teststring) && i + j < inText.length() - 1) { prevstring = teststring; j++; teststring = teststring.concat(String.valueOf(inText.charAt(i + j))); } // get key value for the string that matched Integer mapIndex = (getKeyByValue(dict, prevstring)); // add this key to the encoded outText as string (ASCII 8 bit) outText = // outText.concat(String.valueOf(((char)Integer.parseInt(mapIndex)))); encodedData[outCount] = mapIndex; outCount++; // add to dictionary the string that matched plus the next char in // sequence in inText // test that the new dictionary entry is not in the dictionary and // does not contain the new-line character if (!dict.containsValue(teststring) && teststring.charAt(teststring.length() - 1) != '\n' && dict.size() < dictSize) dict.put(dict.size(), teststring); // set index value i to point to that next char in sequence i = i + j - 1; } // TODO add switch to turn printing on and off System.out.println("\n-- Dictionary --"); printDictionary(dict); returnData = new int[outCount]; // count entries and use here. for (int i = 0; i < outCount; i++) { returnData[i] = encodedData[i]; } encodedData = returnData; } catch (Exception ex) { System.err.println( "---------------------------------------------\nencodeLZW() method failed\nprobably tried to encode an incompatable file\n---------------------------------------------"); return false; } return true; } public static HashMap<Integer, String> newDictLZW(String inMsg) { HashMap<Integer, String> dict = new HashMap<Integer, String>(); int j = 0; for (int i = 0; i < inMsg.length(); i++) { if (dict.containsValue(Character.toString(inMsg.charAt(i))) == false && inMsg.charAt(i) != '\n') { dict.put((Integer) j, Character.toString(inMsg.charAt(i))); j++; } } return dict; } public static Integer getKeyByValue(Map<Integer, String> map, String value) { for (Entry<Integer, String> entry : map.entrySet()) { if (value.equals(entry.getValue())) { return entry.getKey(); } } return null; } public static void printDictionary(HashMap<Integer, String> dict) { System.out.println("Index\t\tEntry\n---------------------"); for (int i = 0; i < dict.size(); i++) { System.out.println(i + "\t\t" + dict.get(i)); } } }