List of usage examples for java.io FileWriter close
public void close() throws IOException
From source file:main.java.utils.Utility.java
public static void deleteLinesFromFile(String filename, int startline, int numlines) { try {/*from ww w . ja va2 s . c o m*/ BufferedReader br = new BufferedReader(new FileReader(filename)); //String buffer to store contents of the file StringBuffer sb = new StringBuffer(""); //Keep track of the line number int linenumber = 1; String line; while ((line = br.readLine()) != null) { //Store each valid line in the string buffer if (linenumber < startline || linenumber >= startline + numlines) sb.append(line + "\n"); linenumber++; } if (startline + numlines > linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw = new FileWriter(new File(filename)); //Write entire string buffer into the file fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: " + e.getMessage()); } }
From source file:com.axelor.apps.tool.file.FileTool.java
/** * Mthode permettant d'crire une ligne dans un fichier * @param destinationFolder//from w w w .ja va 2 s. com * Le chemin du fichier * @param fileName * Le nom du fichier * @param line * La ligne crire * @throws IOException */ public static void writer(String destinationFolder, String fileName, String line) throws IOException { System.setProperty("line.separator", "\r\n"); FileWriter writer = null; try { File file = create(destinationFolder, fileName); writer = new FileWriter(file); writer.write(line); } catch (IOException ex) { LOG.error(ex.getMessage()); } finally { if (writer != null) { writer.close(); } } }
From source file:net.sourceforge.docfetcher.CommandLineHandler.java
/** * Handles command line text extraction. Returns false if the program should * terminate after executing this method, and returns true if the program is * allowed to proceed.//from w ww.j av a 2s. c om */ private static boolean handleTextExtraction(CommandLine line) { if (!line.hasOption(EXTRACT) && !line.hasOption(EXTRACT_DIR)) return true; // Create inclusion and exclusion filters Pattern includeFilter = null; Pattern excludeFilter = null; try { String includeString = line.getOptionValue(INCLUDE); // may be null includeFilter = Pattern.compile(includeString); } catch (Exception e1) { // Ignore } try { String excludeString = line.getOptionValue(EXCLUDE); // may be null excludeFilter = Pattern.compile(excludeString); } catch (Exception e1) { // Ignore } // Get sources and destination boolean writeToDir = false; String[] args1 = null; if (line.hasOption(EXTRACT)) { args1 = line.getOptionValues(EXTRACT); } else { writeToDir = true; args1 = line.getOptionValues(EXTRACT_DIR); } if (args1 == null) args1 = new String[0]; String[] args2 = line.getArgs(); String[] args = UtilList.concatenate(args1, args2, new String[args1.length + args2.length]); if (args.length < 2) { System.out.println("Text extraction requires at least one source and one destination."); return false; } // Create source file objects, check for existence int lastIndex = args.length - 1; File[] topLevelSources = new File[lastIndex]; for (int i = 0; i < topLevelSources.length; i++) { String path = args[i]; File file = new File(path); if (!file.exists()) { System.out.println("File not found: " + path); return false; } topLevelSources[i] = file; } // Check validity of destination File dest = new File(args[lastIndex]); if (writeToDir) { if (dest.exists()) { if (!dest.isDirectory()) { System.out.println("Not a directory: " + dest.getAbsolutePath()); return false; } } else { if (!dest.mkdirs()) { System.out.println("Could not create directory: " + dest.getAbsolutePath()); return false; } } } /* * The source files are collected beforehand because * 1) the text output will depend on the number of files to process, * so we first have to determine how many files there are * 2) the target file(s) might lie inside one of the source directories, * so we first collect all source files in order to avoid confusion * 3) by using a Map, we make sure there aren't any duplicate sources. */ Map<File, Parser> sources = new LinkedHashMap<File, Parser>(); for (File topLevelSource : topLevelSources) collect(topLevelSource, sources, includeFilter, excludeFilter, true); int nSources = sources.size(); // must be set *after* filling the sources list! // Perform text extraction if (writeToDir) { int i = 1; for (Entry<File, Parser> item : sources.entrySet()) { File source = item.getKey(); System.out.println("Extracting (" + i + "/" + nSources + "): " + source.getName()); try { File outFile = UtilFile.getNewFile(dest, source.getName() + ".txt"); String text = item.getValue().renderText(source); FileWriter writer = new FileWriter(outFile, false); writer.write(text); writer.close(); } catch (Exception e) { System.out.println(" Error: " + e.getMessage()); } i++; } } else { // First check that the destination is not one of the source files for (File source : sources.keySet()) { if (source.equals(dest)) { System.out.println("Invalid input: Destination is identical to one of the source files."); return false; } } // If there's only one file to process, don't decorate the text output if (nSources == 1) { Entry<File, Parser> item = sources.entrySet().iterator().next(); System.out.println("Extracting: " + item.getKey().getName()); try { String text = item.getValue().renderText(item.getKey()); FileWriter writer = new FileWriter(dest); writer.write(text); writer.close(); } catch (Exception e) { System.out.println(" Error: " + e.getMessage()); } } // Multiple files to process: else { try { FileWriter writer = new FileWriter(dest, false); // overwrite int i = 1; for (Entry<File, Parser> item : sources.entrySet()) { File source = item.getKey(); System.out.println("Extracting (" + i + "/" + nSources + "): " + source.getName()); try { String text = item.getValue().renderText(source); // This may fail, so do it first writer.write("Source: " + source.getAbsolutePath() + Const.LS); writer.write("============================================================" + Const.LS); writer.write(text); writer.write(Const.LS + Const.LS + Const.LS); } catch (Exception e) { System.out.println(" Error: " + e.getMessage()); } i++; } writer.close(); } catch (IOException e) { System.out.println("Can't write to file: " + e.getMessage()); } } } return false; }
From source file:com.sakadream.sql.SQLConfigJson.java
/** * Save SQLConfig to config.json/*ww w . j av a 2s. c o m*/ * @param sqlConfig SQLConfig object * @param encrypt Are you want to encrypt config.json? * @throws Exception */ public static void save(SQLConfig sqlConfig, Boolean encrypt) throws Exception { File file = new File(path); if (!file.exists()) { file.createNewFile(); } else { FileChannel outChan = new FileOutputStream(file, true).getChannel(); outChan.truncate(0); outChan.close(); } FileWriter writer = new FileWriter(file); String json = gson.toJson(sqlConfig, type); if (encrypt) { Security security = new Security(); writer.write(security.encrypt(json)); } else { writer.write(json); } writer.close(); }
From source file:Main.java
/** * Write the String into the given File/*from w ww . j ava 2s. c om*/ * @param baseString * @param mainStyleFile */ public static void writeStyleFile(String baseString, File mainStyleFile) { FileWriter fw = null; try { fw = new FileWriter(mainStyleFile); fw.write(baseString); Log.i("STYLE", "Style File updated:" + mainStyleFile.getPath()); } catch (FileNotFoundException e) { Log.e("STYLE", "unable to write open file:" + mainStyleFile.getPath()); } catch (IOException e) { Log.e("STYLE", "error writing the file: " + mainStyleFile.getPath()); } finally { try { if (fw != null) { fw.close(); } } catch (IOException e) { // ignored } } }
From source file:com.sakadream.sql.SQLConfigJson.java
/** * Save SQLConfig to custom file name/*from w ww .j ava2 s. c o m*/ * @param fileName SQLConfig file path * @param sqlConfig SQLConfig object * @param encrypt Are you want to encrypt config.json? * @throws Exception */ public static void save(String fileName, SQLConfig sqlConfig, Boolean encrypt) throws Exception { fileName = Utilis.changeFileName(fileName, "json"); File file = new File(fileName); if (!file.exists()) { file.createNewFile(); } else { FileChannel outChan = new FileOutputStream(file, true).getChannel(); outChan.truncate(0); outChan.close(); } FileWriter writer = new FileWriter(file); String json = gson.toJson(sqlConfig, type); if (encrypt) { Security security = new Security(); writer.write(security.encrypt(json)); } else { writer.write(json); } writer.close(); }
From source file:Main.java
public static void writeCSV(String phoneNo, String Message) { File root = Environment.getExternalStorageDirectory(); File csvFile = new File(root, "/adspammer/log.csv"); FileWriter writer = null; try {/*from w ww . ja v a 2 s. c om*/ writer = new FileWriter(csvFile, true); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd @ HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date)); writer.append(dateFormat.format(date).toString()); writer.append(','); writer.append(phoneNo); writer.append(','); writer.append(Message); writer.append('\n'); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.abid_mujtaba.fetchheaders.models.Account.java
private static void writeAccountsToJson() // Reads all Account objects (some of them updated) and uses them to write this data to accounts.json { try {/*w w w. java2 s. co m*/ JSONObject jRoot = new JSONObject(); JSONArray jAccounts = new JSONArray(); for (int ii = 0; ii < sNumOfInstances; ii++) { JSONObject jAccount = new JSONObject(); Account account = sInstances.get(ii); jAccount.put("name", account.name()); jAccount.put("host", account.host()); jAccount.put("username", account.username()); jAccount.put("password", account.password()); jAccounts.put(jAccount); } jRoot.put("accounts", jAccounts); // Save JSON to accounts.json FileWriter fw = new FileWriter(new File(Resources.INTERNAL_FOLDER, Settings.ACCOUNTS_JSON_FILE)); // Write root JSON object to file info.json fw.write(jRoot.toString()); fw.flush(); fw.close(); } catch (JSONException e) { Log.e(Resources.LOGTAG, "Exception raised while manipulate JSON objects.", e); } catch (IOException e) { Log.e(Resources.LOGTAG, "Exception raised while saving content to json file.", e); } }
From source file:com.abiquo.am.services.filesystem.TemplateFileSystem.java
/** * synch to avoid multiple changes on the package folder (before 'clearOVFStatusMarks'). * /* ww w . j av a 2 s .co m*/ * @throws RepositoryException */ public static synchronized void createTemplateStatusMarks(final String enterpriseRepositoryPath, final String ovfId, final TemplateStatusEnumType status, final String errorMsg) { final String packagePath = getTemplatePath(enterpriseRepositoryPath, ovfId); clearTemplateStatusMarks(packagePath); File mark = null; boolean errorCreate = false; try { switch (status) { case DOWNLOAD: // after clean the prev. marks, nothing to do. break; case NOT_DOWNLOAD: // once the OVF envelope (.ovf) is deleted its NOT_FOUND break; case DOWNLOADING: mark = new File(packagePath + '/' + TEMPLATE_STATUS_DOWNLOADING_MARK); errorCreate = !mark.createNewFile(); break; case ERROR: mark = new File(packagePath + '/' + TEMPLATE_STATUS_ERROR_MARK); errorCreate = !mark.createNewFile(); if (!errorCreate) { FileWriter fileWriter = new FileWriter(mark); fileWriter.append(errorMsg); fileWriter.close(); } break; default: throw new AMException(AMError.TEMPLATE_UNKNOW_STATUS, status.name()); }// switch } catch (IOException ioe) { throw new AMException(AMError.TEMPLATE_CHANGE_STATUS, mark.getAbsoluteFile().getAbsolutePath()); } if (errorCreate) { throw new AMException(AMError.TEMPLATE_CHANGE_STATUS, mark.getAbsoluteFile().getAbsolutePath()); } }
From source file:com.dc.util.file.FileSupport.java
public static void appendToFile(File file, String data) throws IOException { FileWriter fileWriter = null; BufferedWriter bufferedWriter = null; try {//w ww . jav a 2 s . c om fileWriter = new FileWriter(file, true); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(data); bufferedWriter.flush(); } finally { if (fileWriter != null) { fileWriter.close(); } if (bufferedWriter != null) { bufferedWriter.close(); } } }