List of usage examples for java.io Writer write
public void write(String str) throws IOException
From source file:com.nary.io.FileUtils.java
public static void writeFile(File outFile, String content) throws IOException { Writer outWriter = null; try {//w w w . j ava 2 s . c om outWriter = cfEngine.thisPlatform.getFileIO().getFileWriter(outFile); outWriter.write(content); outWriter.flush(); } finally { try { if (outWriter != null) outWriter.close(); } catch (Exception ignoreCloseException) { } } }
From source file:modnlp.capte.AlignerUtils.java
public static void reWriteAlignment(String sourcename, String targetname, Vector<Object[]> d) { try {// w w w . j a va2 s. c om FileOutputStream op = new FileOutputStream(sourcename); Writer out = new OutputStreamWriter(op, "UTF-8"); FileOutputStream sp = new FileOutputStream(targetname); Writer sout = new OutputStreamWriter(sp, "UTF-8"); String source = ""; String target = ""; Object[] stemp; for (int i = 0; i < d.size(); i++) { stemp = d.get(i); source = (String) stemp[0]; target = (String) stemp[1]; source = clean(source); target = clean(target); out.write(source); out.write("\n"); sout.write(target); sout.write("\n"); System.out.println(source); System.out.println(target); } out.close(); sout.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:edu.stanford.epad.common.util.EPADFileUtils.java
/** * True if the write succeed otherwise it is false. * /*from www . j a va 2 s. co m*/ * @param file - File including full directory path to write. * @param contents - String complete contents of file. * @return boolean */ public static boolean write(File file, String contents) { try { Writer out = new BufferedWriter(new FileWriter(file)); out.write(contents); out.flush(); out.close(); return true; } catch (Exception e) { log.warning("Failed to write file: " + file.getAbsolutePath(), e); return false; } }
From source file:com.wavemaker.json.JSONMarshaller.java
/** * Recursively write out maps and objects. * //from w w w .j av a2s . c o m * @param writer * @throws IOException */ private static void handleObject(Object obj, Object root, JSONState js, Writer writer, Stack<Object> touchedObjects, Stack<String> propertyNames, boolean sort, FieldDefinition fieldDefinition, int arrayLevel, TypeState typeState, boolean prettyPrint, int level, Logger logger) throws IOException { if (fieldDefinition == null) { throw new NullArgumentException("fieldDefinition"); } writer.write('{'); boolean firstProperty = true; if (obj instanceof Map || fieldDefinition.getTypeDefinition() instanceof MapTypeDefinition) { Set<Entry<?, ?>> entries = null; if (sort) { Set<Entry<?, ?>> entriesTemp = new TreeSet<Entry<?, ?>>(new EntryComparator()); entriesTemp.addAll(((Map<?, ?>) obj).entrySet()); entries = entriesTemp; } for (Entry<?, ?> entry : entries == null ? ((Map<?, ?>) obj).entrySet() : entries) { String key = (String) entry.getKey(); if (fieldDefinition.getTypeDefinition() != null && fieldDefinition.getTypeDefinition() instanceof MapTypeDefinition) { fieldDefinition = ((MapTypeDefinition) fieldDefinition.getTypeDefinition()) .getValueFieldDefinition(); } else { fieldDefinition = new GenericFieldDefinition(); } firstProperty = handleObjectInternal(obj, root, key, entry.getValue(), firstProperty, js, writer, touchedObjects, propertyNames, sort, fieldDefinition, arrayLevel, typeState, prettyPrint, level + 1, logger); } } else if (fieldDefinition.getTypeDefinition() instanceof ObjectTypeDefinition) { ObjectReflectTypeDefinition otd = (ObjectReflectTypeDefinition) fieldDefinition.getTypeDefinition(); if (otd.getKlass().isAssignableFrom(obj.getClass())) { for (Entry<String, FieldDefinition> entry : otd.getFields().entrySet()) { String name = entry.getKey(); fieldDefinition = entry.getValue(); Object value; try { value = PropertyUtils.getProperty(obj, name); } catch (IllegalArgumentException e) { throw new WMRuntimeException(MessageResource.ERROR_GETTING_PROPERTY, e, name, obj, obj.getClass().getName()); } catch (IllegalAccessException e) { throw new WMRuntimeException(MessageResource.ERROR_GETTING_PROPERTY, e, name, obj, obj.getClass().getName()); } catch (InvocationTargetException e) { throw new WMRuntimeException(MessageResource.ERROR_GETTING_PROPERTY, e, name, obj, obj.getClass().getName()); } catch (NoSuchMethodException e) { logger.warn(MessageResource.JSON_NO_GETTER_IN_TYPE.getMessage(name, obj, obj.getClass().getName())); continue; } firstProperty = handleObjectInternal(obj, root, name, value, firstProperty, js, writer, touchedObjects, propertyNames, sort, fieldDefinition, 0, typeState, prettyPrint, level + 1, logger); } } } else { throw new WMRuntimeException(MessageResource.JSON_BAD_HANDLE_TYPE, fieldDefinition.getTypeDefinition()); } if (prettyPrint) { writer.write("\n"); writeIndents(writer, level); } writer.write('}'); }
From source file:com.mail163.email.mail.transport.Rfc822Output.java
/** * Write text (either as main body or inside a multipart), preceded by appropriate headers. * * Note this always uses base64, even when not required. Slightly less efficient for * US-ASCII text, but handles all formats even when non-ascii chars are involved. A small * optimization might be to prescan the string for safety and send raw if possible. * * @param writer the output writer/*from ww w. j a v a 2 s. co m*/ * @param out the output stream inside the writer (used for byte[] access) * @param text The original text of the message */ private static void writeTextWithHeaders(Writer writer, OutputStream out, String text) throws IOException { Logs.v(Logs.LOG_MessageView, "isContentType >>>>>>>>> :" + isContentType); //=============2012.3.4=========== if (isContentType) {//Content-Type writeHeader(writer, "Content-Type", "text/html; charset=utf-8"); } else { writeHeader(writer, "Content-Type", "text/plain; charset=utf-8"); } //=============2012.3.4=========== writeHeader(writer, "Content-Transfer-Encoding", "base64"); writer.write("\r\n"); byte[] bytes = text.getBytes("UTF-8"); writer.flush(); out.write(Base64.encode(bytes, Base64.CRLF)); }
From source file:net.sf.jabref.exporter.FileActions.java
private static void writeString(Writer fw, BibtexString bs, Map<String, BibtexString> remaining, int maxKeyLength) throws IOException { // First remove this from the "remaining" list so it can't cause problem with circular refs: remaining.remove(bs.getName());/*from w w w.j ava 2 s .c o m*/ //if the string has not been modified, write it back as it was if (!bs.hasChanged()) { fw.write(bs.getParsedSerialization()); return; } // Then we go through the string looking for references to other strings. If we find references // to strings that we will write, but still haven't, we write those before proceeding. This ensures // that the string order will be acceptable for BibTeX. String content = bs.getContent(); Matcher m; while ((m = FileActions.REFERENCE_PATTERN.matcher(content)).find()) { String foundLabel = m.group(1); int restIndex = content.indexOf(foundLabel) + foundLabel.length(); content = content.substring(restIndex); Object referred = remaining.get(foundLabel.substring(1, foundLabel.length() - 1)); // If the label we found exists as a key in the "remaining" Map, we go on and write it now: if (referred != null) { FileActions.writeString(fw, (BibtexString) referred, remaining, maxKeyLength); } } if (FileActions.previousStringType != bs.getType()) { fw.write(Globals.NEWLINE); FileActions.previousStringType = bs.getType(); } StringBuilder suffixSB = new StringBuilder(); for (int i = maxKeyLength - bs.getName().length(); i > 0; i--) { suffixSB.append(' '); } String suffix = suffixSB.toString(); fw.write("@String { " + bs.getName() + suffix + " = "); if (!bs.getContent().isEmpty()) { try { String formatted = new LatexFieldFormatter().format(bs.getContent(), LatexFieldFormatter.BIBTEX_STRING); fw.write(formatted); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException( "The # character is not allowed in BibTeX strings unless escaped as in '\\#'.\n" + "Before saving, please edit any strings containing the # character."); } } else { fw.write("{}"); } fw.write(" }" + Globals.NEWLINE); }
From source file:com.xqdev.jam.MLJAM.java
private static void sendXQueryResponse(HttpServletResponse res, Object o) throws IOException { // Make sure to leave the status code alone. It defaults to 200, but sometimes // callers of this method will have set it to a custom code. res.setContentType("x-marklogic/xquery; charset=UTF-8"); //res.setContentType("text/plain"); Writer writer = res.getWriter(); // care to handle errors later? if (o == null) { writer.write("()"); }/* w ww . ja va 2s . c o m*/ else if (o instanceof byte[]) { writer.write("binary {'"); writer.write(hexEncode((byte[]) o)); writer.write("'}"); } else if (o instanceof Object[]) { Object[] arr = (Object[]) o; writer.write("("); for (int i = 0; i < arr.length; i++) { sendXQueryResponse(res, arr[i]); if (i + 1 < arr.length) writer.write(", "); } writer.write(")"); } else if (o instanceof String) { writer.write("'"); writer.write(escapeSingleQuotes(o.toString())); writer.write("'"); } else if (o instanceof Integer) { writer.write("xs:int("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Long) { writer.write("xs:integer("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Float) { Float flt = (Float) o; writer.write("xs:float("); if (flt.equals(Float.POSITIVE_INFINITY)) { writer.write("'INF'"); } else if (flt.equals(Float.NEGATIVE_INFINITY)) { writer.write("'-INF'"); } else if (flt.equals(Float.NaN)) { writer.write("fn:number(())"); // poor man's way to write NaN } else { writer.write(o.toString()); } writer.write(")"); } else if (o instanceof Double) { Double dbl = (Double) o; writer.write("xs:double("); if (dbl.equals(Double.POSITIVE_INFINITY)) { writer.write("'INF'"); } else if (dbl.equals(Double.NEGATIVE_INFINITY)) { writer.write("'-INF'"); } else if (dbl.equals(Double.NaN)) { writer.write("fn:number(())"); // poor man's way to write NaN } else { writer.write(o.toString()); } writer.write(")"); } else if (o instanceof Boolean) { writer.write("xs:boolean('"); writer.write(o.toString()); writer.write("')"); } else if (o instanceof BigDecimal) { writer.write("xs:decimal("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Date) { // We want something like: 2006-04-30T01:28:30.499-07:00 // We format to get: 2006-04-30T01:28:30.499-0700 // Then we add in the colon writer.write("xs:dateTime('"); String d = dateFormat.format((Date) o); writer.write(d.substring(0, d.length() - 2)); writer.write(":"); writer.write(d.substring(d.length() - 2)); writer.write("')"); } else if (o instanceof XMLGregorianCalendar) { XMLGregorianCalendar greg = (XMLGregorianCalendar) o; QName type = greg.getXMLSchemaType(); if (type.equals(DatatypeConstants.DATETIME)) { writer.write("xs:dateTime('"); } else if (type.equals(DatatypeConstants.DATE)) { writer.write("xs:date('"); } else if (type.equals(DatatypeConstants.TIME)) { writer.write("xs:time('"); } else if (type.equals(DatatypeConstants.GYEARMONTH)) { writer.write("xs:gYearMonth('"); } else if (type.equals(DatatypeConstants.GMONTHDAY)) { writer.write("xs:gMonthDay('"); } else if (type.equals(DatatypeConstants.GYEAR)) { writer.write("xs:gYear('"); } else if (type.equals(DatatypeConstants.GMONTH)) { writer.write("xs:gMonth('"); } else if (type.equals(DatatypeConstants.GDAY)) { writer.write("xs:gDay('"); } writer.write(greg.toXMLFormat()); writer.write("')"); } else if (o instanceof Duration) { Duration dur = (Duration) o; /* // The following fails on Xerces QName type = dur.getXMLSchemaType(); if (type.equals(DatatypeConstants.DURATION)) { writer.write("xs:duration('"); } else if (type.equals(DatatypeConstants.DURATION_DAYTIME)) { writer.write("xdt:dayTimeDuration('"); } else if (type.equals(DatatypeConstants.DURATION_YEARMONTH)) { writer.write("xdt:yearMonthDuration('"); } */ // If no years or months, must be DURATION_DAYTIME if (dur.getYears() == 0 && dur.getMonths() == 0) { writer.write("xdt:dayTimeDuration('"); } // If has years or months but nothing else, must be DURATION_YEARMONTH else if (dur.getDays() == 0 && dur.getHours() == 0 && dur.getMinutes() == 0 && dur.getSeconds() == 0) { writer.write("xdt:yearMonthDuration('"); } else { writer.write("xs:duration('"); } writer.write(dur.toString()); writer.write("')"); } else if (o instanceof org.jdom.Element) { org.jdom.Element elt = (org.jdom.Element) o; writer.write("xdmp:unquote('"); // Because "<" in XQuery is the same as "<" I need to double escape any ampersands writer.write(new org.jdom.output.XMLOutputter().outputString(elt).replaceAll("&", "&") .replaceAll("'", "''")); writer.write("')/*"); // make sure to return the root elt } else if (o instanceof org.jdom.Document) { org.jdom.Document doc = (org.jdom.Document) o; writer.write("xdmp:unquote('"); writer.write(new org.jdom.output.XMLOutputter().outputString(doc).replaceAll("&", "&") .replaceAll("'", "''")); writer.write("')"); } else if (o instanceof org.jdom.Text) { org.jdom.Text text = (org.jdom.Text) o; writer.write("text {'"); writer.write(escapeSingleQuotes(text.getText())); writer.write("'}"); } else if (o instanceof org.jdom.Attribute) { // <fake xmlns:pref="http://uri.com" pref:attrname="attrvalue"/>/@*:attrname // <fake xmlns="http://uri.com" attrname="attrvalue"/>/@*:attrname org.jdom.Attribute attr = (org.jdom.Attribute) o; writer.write("<fake xmlns"); if ("".equals(attr.getNamespacePrefix())) { writer.write("=\""); } else { writer.write(":" + attr.getNamespacePrefix() + "=\""); } writer.write(attr.getNamespaceURI()); writer.write("\" "); writer.write(attr.getQualifiedName()); writer.write("=\""); writer.write(escapeSingleQuotes(attr.getValue())); writer.write("\"/>/@*:"); writer.write(attr.getName()); } else if (o instanceof org.jdom.Comment) { org.jdom.Comment com = (org.jdom.Comment) o; writer.write("comment {'"); writer.write(escapeSingleQuotes(com.getText())); writer.write("'}"); } else if (o instanceof org.jdom.ProcessingInstruction) { org.jdom.ProcessingInstruction pi = (org.jdom.ProcessingInstruction) o; writer.write("processing-instruction "); writer.write(pi.getTarget()); writer.write(" {'"); writer.write(escapeSingleQuotes(pi.getData())); writer.write("'}"); } else if (o instanceof QName) { QName q = (QName) o; writer.write("fn:expanded-QName('"); writer.write(escapeSingleQuotes(q.getNamespaceURI())); writer.write("','"); writer.write(q.getLocalPart()); writer.write("')"); } else { writer.write("error('XQuery tried to retrieve unsupported type: " + o.getClass().getName() + "')"); } writer.flush(); }
From source file:com.bristle.javalib.io.FileUtil.java
/************************************************************************** * Copy the contents of the specified binary file to the specified Writer. *@param strFilename Name of the file to copy. *@param writer Writer to write to. *@throws FileNotFoundException/*from w w w .j a v a 2 s. co m*/ * When binary file not found. *@throws IOException When an I/O error occurs reading the file or * writing it to the Writer. **************************************************************************/ public static void copyBinaryFileToWriter(String strFilename, Writer writer) throws FileNotFoundException, IOException { RandomAccessFile file = new RandomAccessFile(strFilename, "r"); try { int i; while (-1 != (i = file.read())) { writer.write((char) i); } writer.flush(); } finally { file.close(); } }
From source file:bridge.toolkit.commands.S1000DConverter.java
/** * Iterate through the DOM tree/*from w w w. ja v a 2 s . c om*/ * * @param node * @param output * @throws IOException */ public static void writeNode(Node node, Writer output) throws IOException { int type = node.getNodeType(); switch (type) { case Node.ATTRIBUTE_NODE: output.write(' '); output.write(node.getNodeName()); output.write("=\""); writeXMLData(node.getNodeValue(), true, output); output.write('"'); break; case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: writeXMLData(node.getNodeValue(), false, output); break; case Node.COMMENT_NODE: output.write("<!--"); output.write(((Comment) node).getNodeValue()); output.write("-->"); break; case Node.DOCUMENT_FRAGMENT_NODE: writeNodes(node.getChildNodes(), output); break; case Node.DOCUMENT_NODE: writeNodes(node.getChildNodes(), output); break; case Node.DOCUMENT_TYPE_NODE: break; case Node.ELEMENT_NODE: { NamedNodeMap atts = node.getAttributes(); output.write('<'); output.write(node.getNodeName()); if (atts != null) { int length = atts.getLength(); for (int i = 0; i < length; i++) writeNode(atts.item(i), output); } if (node.hasChildNodes()) { output.write('>'); writeNodes(node.getChildNodes(), output); output.write("</"); output.write(node.getNodeName()); output.write('>'); } else { output.write("/>"); } break; } case Node.ENTITY_NODE: break; case Node.ENTITY_REFERENCE_NODE: writeNodes(node.getChildNodes(), output); break; case Node.NOTATION_NODE: break; case Node.PROCESSING_INSTRUCTION_NODE: break; default: throw new Error("Unexpected DOM node type: " + type); } }
From source file:dataGen.DataGen.java
/** * Creates normal or uniform distributed Test-Data, without correlation. * The resulting Data is stored in the resources Folder. * @param dimensions//from w w w. j ava2s . co m * The dimension count of the resulting Data * @param rowCount * How many data tuples should be created? * @throws IOException * If Stream to a File couldn't be written/closed */ public static void genData(int dimensions, int rowCount) throws IOException { logger.info("Generating uniform random Data with " + rowCount + " Tuples in " + dimensions + " dimensions"); Writer fw = new FileWriter("src/main/resources/random-" + rowCount + "-" + dimensions + ".dat"); Random gen = new Random(); for (int i = 1; i <= rowCount; i++) { // Each Row should start with the Row count String row = i + " "; // Files should be created OS/Language independent DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setDecimalSeparator('.'); NumberFormat nf = new DecimalFormat("0.000000000", dfs); for (int j = 0; j < dimensions; j++) { Float n = gen.nextFloat(); row = row + nf.format(n) + " "; } fw.write(row); fw.append(System.getProperty("line.separator")); } fw.close(); logger.info(rowCount + " entries generated"); }