List of usage examples for java.io BufferedWriter write
public void write(int c) throws IOException
From source file:eu.smartfp7.foursquare.AttendanceCrawler.java
/** * From GitHub issue: https://github.com/SmartSearch/Foursquare-Attendance-Crawler/issues/3 * /* w w w. j a v a2 s. c o m*/ * Venues can be deleted by/on Foursquare, resulting in errors when the crawler * attempts to retrieve the hourly attendance. It also has bad consequences: the * crawler tries to obtain the attendance over and over, draining the number of * API calls, which also impacts the crawling of other venues and can lead to * missing obervations. * * This function removes a venue from the different files, so that it won't be * considered by the crawler anymore. */ public static void removeVenue(String venue_id, String city) { /** * First part: we need to remove `venue_id` from the ids file. We use a temporary * file to do this. */ String ids_file = Settings.getInstance().getFolder() + city + File.separator + "venues.ids"; String tmp_ids_file = Settings.getInstance().getFolder() + city + File.separator + "venues.ids.tmp"; try { BufferedReader reader = new BufferedReader(new FileReader(ids_file)); BufferedWriter writer = new BufferedWriter(new FileWriter(tmp_ids_file)); String line = null; while ((line = reader.readLine()) != null) { // Skipping `venue_id` when rewriting the file. String trimmedLine = line.trim(); if (trimmedLine.equals(venue_id)) continue; writer.write(line + "\n"); } reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } // When we have finished rewriting, we rename the temporary file so that it // becomes the real one. new File(tmp_ids_file).renameTo(new File(ids_file)); /** End of first part. */ /** * Second part: we need to delete the files related to the venue that have * been created while crawling (i.e. .ts and .info). * Instead, we move them into a .deleted folder that can allow us to recover * from hypothetical errors. */ new File(Settings.getInstance().getFolder() + city + File.separator + "attendances_crawl" + File.separator + venue_id + ".ts") .renameTo(new File(Settings.getInstance().getFolder() + city + File.separator + ".deleted" + File.separator + venue_id + ".ts")); new File(Settings.getInstance().getFolder() + city + File.separator + "foursquare_venues" + File.separator + venue_id + ".info") .renameTo(new File(Settings.getInstance().getFolder() + city + File.separator + ".deleted" + File.separator + venue_id + ".info")); /** End of second part. */ }
From source file:com.almarsoft.GroundhogReader.lib.FSUtils.java
public static void writeReaderToDiskFile(Reader data, String fullPath, String fileName) throws IOException { File outDir = new File(fullPath); if (!outDir.exists()) outDir.mkdirs();// ww w . ja v a2 s . co m BufferedWriter out = null; try { FileWriter writer = new FileWriter(fullPath + fileName); out = new BufferedWriter(writer); String readData = null; char[] buf = new char[1024]; int numRead = 0; while ((numRead = data.read(buf)) != -1) { readData = String.valueOf(buf, 0, numRead); out.write(readData); buf = new char[1024]; } //out.write(data); out.flush(); } finally { if (out != null) out.close(); } }
From source file:edu.iu.daal_kmeans.regroupallgather.KMUtil.java
public static void storeCentroids(Configuration configuration, String cenDir, Table<DoubleArray> cenTable, int cenVecSize, String name) throws IOException { String cFile = cenDir + File.separator + "out" + File.separator + name; Path cPath = new Path(cFile); LOG.info("centroids path: " + cPath.toString()); FileSystem fs = FileSystem.get(configuration); fs.delete(cPath, true);/* w ww .j a v a 2 s . c o m*/ FSDataOutputStream out = fs.create(cPath); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); int linePos = 0; int[] idArray = cenTable.getPartitionIDs().toArray(new int[0]); IntArrays.quickSort(idArray); for (int i = 0; i < idArray.length; i++) { Partition<DoubleArray> partition = cenTable.getPartition(idArray[i]); for (int j = 0; j < partition.get().size(); j++) { linePos = j % cenVecSize; if (linePos == (cenVecSize - 1)) { bw.write(partition.get().get()[j] + "\n"); } else if (linePos > 0) { // Every row with vectorSize + 1 length, // the first one is a count, // ignore it in output bw.write(partition.get().get()[j] + " "); } } } bw.flush(); bw.close(); }
From source file:com.tesora.dve.common.PEFileUtils.java
/** * Write the text out to the specified filename. * /* w w w .j a va 2 s . c om*/ * @param fileName * @param text * @param overwriteContents * @throws Exception */ public static void writeToFile(File file, String text, boolean overwriteContents) throws PEException { BufferedWriter bw = null; try { if (file.exists() && !overwriteContents) throw new PEException("File '" + file.getCanonicalPath() + "' already exists"); createDirectory(file.getParent()); bw = new BufferedWriter(new FileWriter(file)); bw.write(text); } catch (Exception e) { throw new PEException("Failed to write to file", e); } finally { if (bw != null) { try { bw.close(); } catch (Exception e) { // Eat it } } } }
From source file:com.iksgmbh.sql.pojomemodb.utils.FileUtil.java
/** * Uses reader and writer to perform copy * @param sourcefile/*www .j a v a2 s .co m*/ * @param targetFile */ public static void copyTextFile(final File sourcefile, final File targetFile) { if (!sourcefile.exists()) { throw new RuntimeException("Sourcefile does not exist: " + sourcefile.getAbsolutePath()); } if (!sourcefile.isFile()) { throw new RuntimeException("Sourcefile is no file: " + sourcefile.getAbsolutePath()); } final String targetdir = targetFile.getParent(); if (!targetFile.getParentFile().exists()) { throw new RuntimeException("TargetDirectory does not exist: " + targetdir); } BufferedReader in = null; BufferedWriter out = null; try { out = IOEncodingHelper.STANDARD.getBufferedWriter(targetFile); in = IOEncodingHelper.STANDARD.getBufferedReader(sourcefile); int c; while ((c = in.read()) != -1) out.write(c); } catch (Exception e) { throw new RuntimeException("Error copying " + sourcefile.getAbsolutePath() + " to " + targetdir, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw new RuntimeException("Error closing reader " + in, e); } } if (out != null) { try { out.close(); } catch (IOException e) { throw new RuntimeException("Error writer reader " + out, e); } } } }
From source file:gov.nih.nci.cabig.caaers.utils.CaaersSerializerUtil.java
/** * This method writes given content to a xml file. Location of the file is $CATALINA_HOME/logs/serializedfiles/ * @param serializedContent/*from w ww . jav a 2s .c o m*/ */ public static void dumpContentToFile(String content) { BufferedWriter out = null; StringBuilder sb = null; try { if (StringUtils.isEmpty(CATALINA_HOME)) { sb = new StringBuilder(USER_HOME); } else { sb = new StringBuilder(System.getenv("CATALINA_HOME")); sb.append("/logs"); } sb.append("/serializedfiles"); File file = new File(sb.toString()); if (!file.isDirectory()) { file.mkdir(); } sb.append("/session_").append(System.currentTimeMillis()).append(".xml"); out = new BufferedWriter(new FileWriter(sb.toString())); out.write(content); } catch (Exception e) { logger.error("Exception while writing contect to file -- ", e); } finally { try { out.close(); } catch (Exception e) { } } }
From source file:hadoop.UIUCWikifierAppHadoop.java
/** * Read in NER and NE default config files, write out new config files * with appropriate paths then save config file and return its location * @param pathToWikifierFiles/*from w w w . j av a2 s .c o m*/ * @return * @throws IOException * @throws FileNotFoundException */ private static String[] writeNewConfigFiles(String pathToWikifierFiles) throws FileNotFoundException, IOException { String[] configFiles = new String[3]; //read in old ner config parameters and change List<String> nerConfigLines = IOUtils .readLines(new FileInputStream(new File(pathToWikifierFiles + "/" + pathToDefaultNERConfigFile))); List<String> newNERConfigLines = new ArrayList<String>(); for (String l : nerConfigLines) { String[] values = l.split("\\t+"); StringBuilder newLine = new StringBuilder(); for (String value : values) { if (value.contains("/")) { newLine.append(pathToWikifierFiles + "/" + value); newLine.append("\t"); } else { newLine.append(value); newLine.append("\t"); } } newNERConfigLines.add(newLine.toString().trim()); } //write out new config parameters File newNERConfigFile = File.createTempFile("NER.config", ".tmp"); newNERConfigFile.deleteOnExit(); configFiles[0] = newNERConfigFile.getAbsolutePath(); BufferedWriter nerWriter = new BufferedWriter(new FileWriter(newNERConfigFile)); for (String l : newNERConfigLines) { System.out.println(l); nerWriter.write(l + "\n"); } nerWriter.close(); //read in old ne config parameters and change List<String> neConfigLines = IOUtils .readLines(new FileInputStream(new File(pathToWikifierFiles + "/" + pathToDefaultNEConfigFile))); List<String> newNEConfigLines = new ArrayList<String>(); for (String l : neConfigLines) { String[] values = l.split("="); String value = values[1]; if (value.contains("/")) { String[] paths = value.split("\\s+"); StringBuilder newValue = new StringBuilder(); for (String path : paths) { newValue.append(pathToWikifierFiles + "/" + path); newValue.append(" "); } StringBuilder newLine = new StringBuilder(); newLine.append(values[0]); newLine.append("="); newLine.append(newValue.toString().trim()); newNEConfigLines.add(newLine.toString()); } else { newNEConfigLines.add(l); } } //write out new config parameters File newNEConfigFile = File.createTempFile("config.txt", ".tmp"); newNEConfigFile.deleteOnExit(); configFiles[1] = newNEConfigFile.getAbsolutePath(); BufferedWriter neWriter = new BufferedWriter(new FileWriter(newNEConfigFile)); for (String l : newNEConfigLines) { neWriter.write(l + "\n"); } neWriter.close(); //read in old wordnet properties List<String> wordNetPropertiesLines = IOUtils .readLines(new FileInputStream(new File(pathToWikifierFiles + "/" + pathToDefaultJWNLConfigFile))); List<String> newWordNetPropertiesLines = new ArrayList<String>(); String replacementString = pathToWikifierFiles + "/data/WordNet/"; String stringToReplace = "data/WordNet/"; for (String l : wordNetPropertiesLines) { if (l.contains("dictionary_path")) { newWordNetPropertiesLines.add(l.replace(stringToReplace, replacementString)); } else { newWordNetPropertiesLines.add(l); } } File newWNConfigFile = File.createTempFile("jwnl_properties.xml", ".tmp"); newWNConfigFile.deleteOnExit(); configFiles[2] = newWNConfigFile.getAbsolutePath(); BufferedWriter wnWriter = new BufferedWriter(new FileWriter(newWNConfigFile)); for (String l : newWordNetPropertiesLines) { wnWriter.write(l + "\n"); } wnWriter.close(); return configFiles; }
From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java
public static void runonfileValidJson(String input_filename, String output_filename) throws IOException { InputStream fis;/* ww w. j av a2 s . c om*/ BufferedReader bufferdReader; String line; try { File file = new File(output_filename); if (file.createNewFile()) { logger.warn("File has been created"); } //else { // logger.info("File already exists."); //} // if (!file.getParentFile().mkdirs()) // throw new IOException("Unable to create " + // file.getParentFile()); FileWriter fileWriter = new FileWriter(output_filename, false); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); String parsedLine; fis = new FileInputStream(input_filename); bufferdReader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8"))); while ((line = bufferdReader.readLine()) != null) { parsedLine = runOnStringJson(new Text(line), output_filename) + "\n"; bufferedWriter.write(parsedLine); } bufferedWriter.close(); bufferdReader.close(); } catch (IOException e) { logger.error("Error writing to file '" + output_filename + "'"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } logger.info("Ouput written to " + output_filename); }
From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java
/** * @param vehicleDistances//from w w w .j a v a 2 s . c om * @param iterationFilename */ public static void writeVehicleDistances(Map<Id<Vehicle>, double[]> vehicleDistances, String iterationFilename) { String header = "vehicleId;drivenDistance_m;occupiedDistance_m;emptyDistance_m;revenueDistance_pm"; BufferedWriter bw = IOUtils.getBufferedWriter(iterationFilename); DecimalFormat format = new DecimalFormat(); format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(2); format.setGroupingUsed(false); try { bw.write(header); for (Entry<Id<Vehicle>, double[]> e : vehicleDistances.entrySet()) { double drivenDistance = e.getValue()[0]; double revenueDistance = e.getValue()[1]; double occDistance = e.getValue()[2]; double emptyDistance = drivenDistance - occDistance; bw.newLine(); bw.write(e.getKey().toString() + ";" + format.format(drivenDistance) + ";" + format.format(occDistance) + ";" + format.format(emptyDistance) + ";" + format.format(revenueDistance)); } bw.flush(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.elastica.helper.FileUtility.java
/** * Saves HTML Source./* w w w. jav a2 s.c o m*/ * * @param path * * @throws Exception */ public static void writeToFile(final String path, final String content) throws IOException { System.gc(); FileOutputStream fileOutputStream = null; OutputStreamWriter outputStreamWriter = null; BufferedWriter bw = null; try { File parentDir = new File(path).getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } fileOutputStream = new FileOutputStream(path); outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF8"); bw = new BufferedWriter(outputStreamWriter); bw.write(content); } finally { if (bw != null) { try { bw.close(); } catch (Exception e) { e.printStackTrace(); } } if (outputStreamWriter != null) { try { outputStreamWriter.close(); } catch (Exception e) { e.printStackTrace(); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } }