write String To File - Java File Path IO

Java examples for File Path IO:Text File

Description

write String 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);
    public static void writeStringToFile(String filename, String content,
            boolean overwrite) {
        File destFile = new File(filename);
        try {/*from  w  w  w  .j  a  va2  s .c o  m*/
            if (destFile.exists()) {
                if (overwrite)
                    destFile.delete();
                else
                    return;
            }
            destFile.createNewFile();
            DataOutputStream outputStream = new DataOutputStream(
                    new FileOutputStream(destFile));
            outputStream.writeBytes(content);
            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