File Compressor : File Commands « File Input Output « Java






File Compressor

       
//package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class FileCompressor {

    private Map<String, Integer>   countMap;

    private List<String>           topWords;

    private Map<String, Character> map;

    private static final char[]    WORDS =
                                             {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
        'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    public String compress(String context) {

        context = context.toLowerCase();
        preprocess(context);
        StringBuilder mapLine = new StringBuilder();
        for (Entry<String, Character> e : map.entrySet()) {
            String key = e.getKey();
            String value = e.getValue().toString();
            context = context.replace(key, value);
            mapLine.append(key);
            mapLine.append(value);
        }
        mapLine.append(System.getProperty("line.separator"));

        StringBuilder out = new StringBuilder(context);
        out.insert(0, mapLine.toString());

        map = null;

        return out.toString();
    }

    public String decompress(String context) throws IOException {
        // process map line
        BufferedReader reader = new BufferedReader(new StringReader(context));
        String mapLine = reader.readLine();
        mapLineprocess(mapLine);

        // create content without mapline
        StringBuilder out = new StringBuilder();
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            out.append(tmp);
            out.append(System.getProperty("line.separator"));
        }

        context = out.toString();
        for (Entry<String, Character> e : map.entrySet()) {
            String key = e.getKey();
            String value = e.getValue().toString();
            context = context.replace(value, key);
        }

        return context;

    }

    private void mapLineprocess(String mapLine) {
        // create map for character replacement
        if (map == null) {
            map = new HashMap<String, Character>();
        }

        char[] line = mapLine.toCharArray();
        StringBuilder key = new StringBuilder();
        for (int i = 0; i < line.length; i += 3) {
            key.append(line[i]);
            key.append(line[i + 1]);
            map.put(key.toString(), line[i + 2]);
            key.setLength(0);
        }
    }

    private void preprocess(String content) {
        // count and get top used words
        count(content);

        // create map for character replacement
        if (map == null) {
            map = new HashMap<String, Character>();
        }
        for (int i = 0; i < WORDS.length && i < topWords.size(); i++) {
            map.put(topWords.get(i), WORDS[i]);
        }
        topWords = null;
    }

    private boolean isBreakLine(char ch) {
        char[] breakLine = System.getProperty("line.separator").toCharArray();
        for (char c : breakLine) {
            if (c == ch)
                return true;
        }
        return false;
    }

    private void count(String content) {
        if (countMap == null) {
            countMap = new HashMap<String, Integer>();
        }
        char[] chs = content.toCharArray();

        StringBuilder bytestr = new StringBuilder();

        // count
        for (char ch : chs) {
            if (isBreakLine(ch))
                continue;
            bytestr.append(ch);
            if (bytestr.length() == 2) {
                int count = 0;
                if (countMap.containsKey(bytestr.toString())) {
                    count = countMap.get(bytestr.toString());
                }
                countMap.put(bytestr.toString(), ++count);
                bytestr.setLength(0);
            }
        }

        // sort
        List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>();
        lists.addAll(countMap.entrySet());
        Collections.sort(lists, new Comparator<Entry<String, Integer>>() {

            @Override
            public int compare(Entry<String, Integer> pO1, Entry<String, Integer> pO2) {
                return pO2.getValue().compareTo(pO1.getValue());
            }
        });

        // to top words
        if (topWords == null) {
            topWords = new ArrayList<String>();
        }
        for (int i = 0; i < WORDS.length && i < lists.size(); i++) {
            topWords.add(i, lists.get(i).getKey());
        }

        countMap = null;

    }

    public static void main(String[] args) throws IOException {

        String file = "D:\\XJad.rar.txt";
        BufferedReader reader = new BufferedReader(new FileReader(file));
        BufferedWriter writer = new BufferedWriter(new FileWriter(file + "_out.txt"));
        StringBuilder content = new StringBuilder();
        String tmp;

        while ((tmp = reader.readLine()) != null) {
            content.append(tmp);
            content.append(System.getProperty("line.separator"));
        }

        FileCompressor f = new FileCompressor();
        writer.write(f.compress(content.toString()));

        writer.close();
        reader.close();

        reader = new BufferedReader(new FileReader(file + "_out.txt"));
        StringBuilder content2 = new StringBuilder();

        while ((tmp = reader.readLine()) != null) {
            content2.append(tmp);
            content2.append(System.getProperty("line.separator"));
        }

        String decompressed = f.decompress(content2.toString());
        String c = content.toString();
        System.out.println(decompressed.equals(c));
    }
}

   
    
    
    
    
    
    
  








Related examples in the same category

1.Touch: set File Last Modified Time
2.File Copy in Java with NIO
3.File Copy in Java
4.Counts words in a file, outputs results in sorted form
5.Copying a file using channels and buffers
6.Copy files using Java IO APICopy files using Java IO API
7.Mimic the Unix Grep command
8.Grep tools
9.BGrep: a regular expression search utility, like Unix grep
10.File concatenation
11.Compress files using the Java ZIP API
12.Delete file using Java IO API
13.Undent - remove leading spaces
14.TeePrintStream tees all PrintStream operations into a file, rather like the UNIX tee(1) command
15.Delete a file from within Java, with error handling
16.DirTree - directory lister, like UNIX ls or DOS and VMS dirDirTree - directory lister, like UNIX ls or DOS and VMS dir
17.Program to empty a directory
18.Report on a file's status in Java
19.Simple directory lister
20.Readonly Files
21.List root directoryList root directory
22.Rename a file in Java
23.FNFilter - directory lister using FilenameFilter
24.mkdir examples
25.Program to remove files matching a name in a directory
26.Ls directory lister modified to use FilenameFilterLs directory lister modified to use FilenameFilter
27.Move a File
28.Word Count
29.Diff: text file difference utility.Diff: text file difference utility.
30.Count chars in a File
31.Move File
32.Get file date and time
33.Return readable file size with selected value measure
34.Move a file
35.Recursive Delete File
36.Read number of lines from a File
37.Copy and overwrite files