Java tutorial
//package com.java2s; //License from project: Apache License import android.util.*; import java.io.*; import java.util.*; public class Main { public static void writeToFile(Collection<?> collection, File file) throws IOException { if (collection != null && file != null) { file.getParentFile().mkdirs(); File tempFile = new File(file.getAbsolutePath() + ".tmp"); FileWriter fw = new FileWriter(tempFile); for (Object obj : collection) { fw.write(new StringBuilder(obj.toString()).append("\r\n").toString()); } fw.flush(); fw.close(); file.delete(); tempFile.renameTo(file); } } public static void writeToFile(Iterator<?> iter, File file) throws IOException { if (iter != null && file != null) { file.getParentFile().mkdirs(); File tempFile = new File(file.getAbsolutePath() + ".tmp"); FileWriter fw = new FileWriter(tempFile); for (; iter.hasNext();) { fw.write(new StringBuilder(iter.next().toString()).append("\r\n").toString()); } fw.flush(); fw.close(); file.delete(); tempFile.renameTo(file); } } public static void close(Closeable closable) { if (closable != null) { try { closable.close(); } catch (IOException e) { e.printStackTrace(); } } } public static boolean delete(File file) { file.setWritable(true); try { if (!file.delete()) { FileOutputStream fos = new FileOutputStream(file); fos.write(0); fos.flush(); fos.close(); } Log.d("delete", "Deleted file: " + file + " successfully"); return true; } catch (IOException e) { Log.d("delete", "The deleting file: " + file + " is not successfully", e); return false; } } private static void delete(File file, StringBuilder sb) { long length = file.length(); boolean deleted = file.delete(); if (deleted) { sb.append(file.getAbsolutePath() + " length " + length + " bytes, deleted.\r\n"); } else { sb.append(file.getAbsolutePath() + " length " + length + " bytes, can't delete.\r\n"); } } }