List of usage examples for java.io BufferedWriter BufferedWriter
public BufferedWriter(Writer out)
From source file:com.galenframework.tests.utils.GalenUtilsTest.java
@Test public void shouldReadRelativePath() throws Exception { File baseDir = new File(System.getProperty("java.io.tmpdir")); File tempDir = new File(baseDir, "galen_test"); tempDir.mkdir();// w ww. j ava 2 s . c o m File testFile1 = new File(tempDir, "testFile.txt"); BufferedWriter output = new BufferedWriter(new FileWriter(testFile1)); output.write(""); output.close(); File testFile2 = new File(baseDir, "testFile2.txt"); BufferedWriter output2 = new BufferedWriter(new FileWriter(testFile2)); output2.write(""); output2.close(); InputStream fileStream1 = GalenUtils.findFileOrResourceAsStream(testFile1.getAbsolutePath()); assertThat(fileStream1, notNullValue()); InputStream fileStream2 = GalenUtils.findFileOrResourceAsStream( tempDir.toString() + File.separator + ".." + File.separator + "testFile2.txt"); assertThat(fileStream2, notNullValue()); FileUtils.deleteQuietly(tempDir); FileUtils.deleteQuietly(testFile2); }
From source file:CSVWriter.java
/** * Writes a table model to csv formatted file * // w ww.j a v a 2 s . c om * @param file * file to create * @param model * model to write * @throws IOException */ public void write(File file, CSVTableModel model, char separator) throws IOException { /* create file */ FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); String value; /* write columns */ if (model.areColumnsVisible()) { for (int column = 0; column < model.getColumnCount(); column++) { value = encodeValue(model.getColumnName(column), separator); bw.write(value); if (column < model.getColumnCount() - 1) { bw.write(separator); } else { bw.newLine(); } } } /* write data */ for (int row = 0; row < model.getRowCount(); row++) { for (int column = 0; column < model.getColumnCount(); column++) { value = encodeValue(model.getValueAt(row, column), separator); bw.write(value); if (column < model.getColumnCount() - 1) { bw.write(separator); } else { bw.newLine(); } } } /* close file */ bw.close(); }
From source file:de.huberlin.wbi.hiway.common.Worker.java
protected static void writeEntryToLog(JsonReportEntry entry) throws IOException { try (BufferedWriter writer = new BufferedWriter( new FileWriter(new File(Invocation.REPORT_FILENAME), true))) { writer.write(entry.toString() + "\n"); }//from www. jav a 2 s .com }
From source file:com.machinelinking.converter.ScriptableConverterTest.java
@Test public void testConvert() throws IOException, ConverterException, ScriptableFactoryException { final String script = IOUtils .toString(this.getClass().getResourceAsStream("scriptable-converter-test1.py")); final ScriptableConverter converter = ScriptableConverterFactory.getInstance().createConverter(script); final ByteArrayOutputStream serializerBAOS = new ByteArrayOutputStream(); final JSONSerializer serializer = new JSONSerializer(serializerBAOS); final ByteArrayOutputStream writerBAOS = new ByteArrayOutputStream(); final Writer writer = new BufferedWriter(new OutputStreamWriter(writerBAOS)); converter.convertData(JSONUtils//from w w w.j a v a2s . c o m .parseJSONAsMap("{\"@type\":\"reference\",\"label\":\"List of Nobel laureates in Physics\"," + "\"content\":{\"@an0\":\"1921\"}}"), serializer, writer); serializer.close(); writer.close(); Assert.assertEquals(serializerBAOS.toString(), "{\"link\":\"List of Nobel laureates in Physics 1921\"}"); Assert.assertEquals(writerBAOS.toString(), "<a href=\"List of Nobel laureates in Physics\">1921</a>"); }
From source file:fileoperations.FileOperations.java
public static boolean writeObjectToFile(Object ObjectToWrite, String fileToWrite) { loggerObj.log(Level.INFO, "inside writeObjectToFile method"); BufferedWriter bw = null;//from ww w .j a va 2s . c o m loggerObj.log(Level.INFO, "File to write the object is:" + fileToWrite); File file = new File(fileToWrite); try { if (!file.exists()) { file.createNewFile(); loggerObj.log(Level.INFO, "File did not exist before: so created new one with the name: " + fileToWrite); } FileWriter fw = new FileWriter(file, true); bw = new BufferedWriter(fw); bw.write(ObjectToWrite.toString()); } catch (IOException ex) { loggerObj.log(Level.SEVERE, "Error in writing to the file:" + fileToWrite + "\n Exception is " + ex.toString()); return false; } catch (Exception ex) { loggerObj.log(Level.SEVERE, "Error in writing to the file:" + fileToWrite + "\n Exception is " + ex.toString()); return false; } finally { try { if (bw != null) { bw.close(); } } catch (IOException ex) { loggerObj.log(Level.SEVERE, "Error in closing the file:" + fileToWrite + " after reading"); return false; } } loggerObj.log(Level.INFO, "Successfully written the object to: " + fileToWrite); return true; }
From source file:Main.java
public static void exportXmlFile(ArrayList<?> listObject, String rootElement, String interfaceName, String pathSaveFile) {//from w ww .j av a2s.c o m try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = builderFactory.newDocumentBuilder(); // creating a new instance of a DOM to build a DOM tree. Document doc = docBuilder.newDocument(); Element root = doc.createElement(rootElement); // adding a node after the last child node of the specified node. doc.appendChild(root); Element interfaceElement = null; Element child = null; Text text; for (Object obj : listObject) { Class srcClass = obj.getClass(); Field[] field = srcClass.getFields(); interfaceElement = doc.createElement(interfaceName); for (int i = 0; i < field.length; i++) { // System.out.println(field[i].getName() + ":" + // field[i].get(obj)); child = doc.createElement(field[i].getName()); text = doc.createTextNode((field[i].get(obj)).toString()); child.appendChild(text); interfaceElement.appendChild(child); } root.appendChild(interfaceElement); } // TransformerFactory instance is used to create Transformer // objects. TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = sw.toString(); File file = new File(pathSaveFile); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); bw.write(xmlString); bw.flush(); bw.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:edu.isi.bmkeg.uimaBioC.elasticSearch.UimaBioCAppConfiguration.java
void urlToTextFile(URL url, File f) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true))); BufferedReader in2 = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine2;/* w w w . ja v a2 s. c o m*/ while ((inputLine2 = in2.readLine()) != null) out.println(inputLine2); in2.close(); out.close(); }
From source file:edu.iu.kmeans.regroupallgather.KMUtil.java
/** * Generate centroids and upload to the cDir * //from w w w.j a va 2s . com * @param numCentroids * @param vectorSize * @param configuration * @param random * @param cenDir * @param fs * @throws IOException */ static void generateCentroids(int numCentroids, int vectorSize, Configuration configuration, Path cenDir, FileSystem fs) throws IOException { Random random = new Random(); double[] data = null; if (fs.exists(cenDir)) fs.delete(cenDir, true); if (!fs.mkdirs(cenDir)) { throw new IOException("Mkdirs failed to create " + cenDir.toString()); } data = new double[numCentroids * vectorSize]; for (int i = 0; i < data.length; i++) { // data[i] = 1000; data[i] = random.nextDouble() * 1000; } Path initClustersFile = new Path(cenDir, Constants.CENTROID_FILE_NAME); System.out.println("Generate centroid data." + initClustersFile.toString()); FSDataOutputStream out = fs.create(initClustersFile, true); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); for (int i = 0; i < data.length; i++) { if ((i % vectorSize) == (vectorSize - 1)) { bw.write(data[i] + ""); bw.newLine(); } else { bw.write(data[i] + " "); } } bw.flush(); bw.close(); System.out.println("Wrote centroids data to file"); }
From source file:fr.calamus.common.tools.AbstractTxtFileAccess.java
/** * Prepares the file for writing; if the file exists, deletes it before. * @return/*from w ww . j av a 2 s .co m*/ * @throws IOException */ protected BufferedWriter prepareBufferedWriter() throws IOException { File f = getFile(); if (!f.getParentFile().exists()) f.getParentFile().mkdirs(); if (f.exists()) { f.delete(); //log.debug("prepareBufferedWriter : " + f.getAbsolutePath() + " deleted"); } f.createNewFile(); //log.debug("prepareBufferedWriter : " + f.getAbsolutePath() + " created"); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(f), Charset.forName(charset))); return bw; }
From source file:org.jnap.core.assets.HandlebarsAssetsHandler.java
@Override public void handle() { final Handlebars handlebars = new Handlebars(); try {//from w ww .j a v a 2 s.c o m Resource[] resources = this.resourceResolver.getResources(source); Resource destRes = new ServletContextResource(servletContext, destination); resetResource(destRes); BufferedWriter writer = new BufferedWriter( new FileWriterWithEncoding(destRes.getFile(), this.encoding, true)); writer.write("(function() {"); writer.write(IOUtils.LINE_SEPARATOR); writer.write("var template = Handlebars.template, "); writer.write("templates = Handlebars.templates = Handlebars.templates || {};"); writer.write(IOUtils.LINE_SEPARATOR); final Set<String> templateNames = new TreeSet<String>(); for (Resource resource : resources) { Template template = handlebars .compile(StringUtils.trimToEmpty(IOUtils.toString(resource.getInputStream()))); final String templateName = FilenameUtils.getBaseName(resource.getFilename()); templateNames.add(templateName); writer.write("templates[\"" + templateName + "\"] = "); writer.write("template("); writer.write(template.toJavaScript()); writer.write(");"); writer.write(IOUtils.LINE_SEPARATOR); } writer.write(IOUtils.LINE_SEPARATOR); if (this.bindToBackboneView) { writer.write("$(function() {"); writer.write(IOUtils.LINE_SEPARATOR); for (String templateName : templateNames) { writer.write(format("if (window[\"{0}\"]) {0}.prototype.template " + "= templates[\"{0}\"];", templateName)); writer.write(IOUtils.LINE_SEPARATOR); } writer.write("});"); writer.write(IOUtils.LINE_SEPARATOR); } writer.write("})();"); IOUtils.closeQuietly(writer); } catch (Exception e) { e.printStackTrace(); } }