write Map To File - Java java.io

Java examples for java.io:OutputStream

Description

write Map To File

Demo Code


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.log4j.Logger;

public class Main{
    private static Logger logger = Logger
            .getLogger(FileAndDatastructureUtil.class);
    /**/*from   w  ww . ja  v a2s .co  m*/
     * @param map
     * @param filename
     * @param overwrite
     * @param separator
     */
    public static void writeMapToFile(LinkedHashMap<String, Integer> map,
            String filename, boolean overwrite, String separator) {
        File destFile = new File(filename);
        System.out.print("WRITING MAP TO FILE "
                + destFile.getAbsolutePath() + "\n");
        logger.debug("WRITING MAP TO FILE " + destFile.getAbsolutePath());
        try {
            if (destFile.exists()) {
                if (overwrite)
                    destFile.delete();
                else
                    return;
            }
            destFile.createNewFile();
            DataOutputStream outputStream = new DataOutputStream(
                    new FileOutputStream(destFile));
            Set<Entry<String, Integer>> s = map.entrySet();
            Iterator<Entry<String, Integer>> it = s.iterator();
            while (it.hasNext()) {
                Entry<String, Integer> entry = it.next();
                outputStream.writeBytes(entry.getKey() + separator
                        + entry.getValue() + "\n");
            }

            outputStream.close();
        } catch (IOException e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }

    }
    /**
     * Given a string representing a file determines whether the file exists.
     * @param filename the string representing the path of the file.
     * @return tru if the file exists, false otherwise.
     */
    public static boolean exists(String filename) {
        File f = new File(filename);
        return f.exists();
    }
}

Related Tutorials