Here you can find the source of writeFile(String content, String path)
Parameter | Description |
---|---|
content | the content be written to file . |
path | the file path . |
public static File writeFile(String content, String path)
//package com.java2s; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.List; public class Main { /**/*from w ww . ja v a 2 s . c om*/ * write the content to file . * * @param content * the content be written to file . * @param path * the file path . * @return */ public static File writeFile(String content, String path) { File f = new File(path); if (!f.exists()) { try { if (f.isFile()) { File dir = new File(f.getParent()); if (!dir.exists()) dir.mkdirs(); } f.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "utf-8")); bw.write(content); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return f; } /** * write multiline data to file . * * @param lines * @param path */ public static void writeFile(List<String> lines, String path) { File f = new File(path); BufferedWriter bw = null; String separator = System.getProperty("line.separator"); if (!f.exists() && lines.size() > 0) { try { f.createNewFile(); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "utf-8")); for (String line : lines) { bw.write(line + separator); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }