Java tutorial
//package com.java2s; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** * write file * * @param filePath * @param content * @param append * is append, if true, write to the end of file, else clear content of file and write into it * @return return true * @throws IOException * if an error occurs while operator FileWriter */ public static boolean writeFile(String filePath, String content, boolean append) { FileWriter fileWriter = null; try { fileWriter = new FileWriter(filePath, append); fileWriter.write(content); fileWriter.close(); return true; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } } } } /** * write file * * @param filePath * @param stream * @return return true * @throws IOException * if an error occurs while operator FileWriter */ public static boolean writeFile(String filePath, InputStream stream) { OutputStream o = null; try { o = new FileOutputStream(filePath); byte data[] = new byte[1024]; int length = -1; while ((length = stream.read(data)) != -1) { o.write(data, 0, length); } o.flush(); return true; } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException occurred. ", e); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { if (o != null) { try { o.close(); stream.close(); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } } } } public static void write(File file, String data) { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file), 1024); out.write(data); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }