Java examples for File Path IO:Text File
write Strings To File
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 w w. j a v a 2s . c o m * @param filename * @param strings * @param overwrite */ public static void writeStringsToFile(String filename, Collection<String> strings, boolean overwrite) { File destFile = new File(filename); try { if (destFile.exists()) { if (overwrite) destFile.delete(); else return; } destFile.createNewFile(); DataOutputStream outputStream = new DataOutputStream( new FileOutputStream(destFile)); outputStream.writeBytes("\n"); Iterator<String> it = strings.iterator(); while (it.hasNext()) { String string = it.next() + "\n"; outputStream.writeBytes(string); } 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(); } }