Java Code Examples for java.io.Writer.write()

The following are Jave code examples for showing how to use write() of the java.io.Writer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: hadoop   File: TestFixedLengthInputFormat.java   Source Code and License Vote up 6 votes
private ArrayList<String> createFile(Path targetFile, CompressionCodec codec,
                                     int recordLen,
                                     int numRecords) throws IOException {
  ArrayList<String> recordList = new ArrayList<String>(numRecords);
  OutputStream ostream = localFs.create(targetFile);
  if (codec != null) {
    ostream = codec.createOutputStream(ostream);
  }
  Writer writer = new OutputStreamWriter(ostream);
  try {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < numRecords; i++) {
      for (int j = 0; j < recordLen; j++) {
        sb.append(chars[charRand.nextInt(chars.length)]);
      }
      String recordData = sb.toString();
      recordList.add(recordData);
      writer.write(recordData);
      sb.setLength(0);
    }
  } finally {
    writer.close();
  }
  return recordList;
}
 
Example 2
Project: Telejam   File: MarkdownTextWriter.java   Source Code and License Vote up 6 votes
private void endEntity(Entry<Attribute, Object> entry, Writer writer) throws IOException {
  if (entry == null) {
    return;
  }

  Attribute entity = entry.getKey();
  if (entity == TextEntity.BOLD) {
    writer.write('*');
  } else if (entity == TextEntity.ITALIC) {
    writer.write('_');
  } else if (entity == TextEntity.CODE) {
    writer.write('`');
  } else if (entity == TextEntity.CODE_BLOCK) {
    writer.write("```");
  } else if (entity == TextEntity.LINK) {
    writer.write("](" + entry.getValue() + ')');
  } else if (entity == TextEntity.TEXT_MENTION) {
    User user = (User) entry.getValue();
    writer.write("](" + TextEntity.TEXT_MENTION_LINK + user.getId() + ")");
  }
}
 
Example 3
Project: elasticsearch_my   File: Streams.java   Source Code and License Vote up 6 votes
/**
 * Copy the contents of the given Reader to the given Writer.
 * Closes both when done.
 *
 * @param in  the Reader to copy from
 * @param out the Writer to copy to
 * @return the number of characters copied
 * @throws IOException in case of I/O errors
 */
public static int copy(Reader in, Writer out) throws IOException {
    Objects.requireNonNull(in, "No Reader specified");
    Objects.requireNonNull(out, "No Writer specified");
    boolean success = false;
    try {
        int byteCount = 0;
        char[] buffer = new char[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        success = true;
        return byteCount;
    } finally {
        if (success) {
            IOUtils.close(in, out);
        } else {
            IOUtils.closeWhileHandlingException(in, out);
        }
    }
}
 
Example 4
Project: hadoop   File: TestFixedLengthInputFormat.java   Source Code and License Vote up 6 votes
private ArrayList<String> createFile(Path targetFile, CompressionCodec codec,
                                     int recordLen,
                                     int numRecords) throws IOException {
  ArrayList<String> recordList = new ArrayList<String>(numRecords);
  OutputStream ostream = localFs.create(targetFile);
  if (codec != null) {
    ostream = codec.createOutputStream(ostream);
  }
  Writer writer = new OutputStreamWriter(ostream);
  try {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < numRecords; i++) {
      for (int j = 0; j < recordLen; j++) {
        sb.append(chars[charRand.nextInt(chars.length)]);
      }
      String recordData = sb.toString();
      recordList.add(recordData);
      writer.write(recordData);
      sb.setLength(0);
    }
  } finally {
    writer.close();
  }
  return recordList;
}
 
Example 5
Project: hadoop   File: TestServer.java   Source Code and License Vote up 5 votes
@Test
@TestDir
public void loadingSiteConfig() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();
  File configFile = new File(dir, "testserver-site.xml");
  Writer w = new FileWriter(configFile);
  w.write("<configuration><property><name>testserver.a</name><value>site</value></property></configuration>");
  w.close();
  Server server = new Server("testserver", dir, dir, dir, dir);
  server.init();
  assertEquals(server.getConfig().get("testserver.a"), "site");
}
 
Example 6
Project: tbschedule-wed   File: ScheduleStrategyDataManager4ZK.java   Source Code and License Vote up 5 votes
/**
 * 输出配置信息【目前备份baseTaskType和strategy数据】
 * 
 * @param rootPath
 * @param writer
 * @throws Exception
 */
public StringBuffer exportConfig(String rootPath, Writer writer)
		throws Exception {
	StringBuffer buffer = new StringBuffer();
	for (String type : new String[] { "baseTaskType", "strategy" }) {
		if (type.equals("baseTaskType")) {
			writer.write("<h2>基本任务配置列表:</h2>\n");
		} else {
			writer.write("<h2>基本策略配置列表:</h2>\n");
		}
		String bTTypePath = rootPath + "/" + type;
		List<String> fNodeList = getZooKeeper().getChildren(bTTypePath,
				false);
		for (int i = 0; i < fNodeList.size(); i++) {
			String fNode = fNodeList.get(i);
			ConfigNode configNode = new ConfigNode(rootPath, type, fNode);
			configNode.setValue(new String(this.getZooKeeper().getData(bTTypePath + "/" + fNode,false,null)));
			buffer.append(gson.toJson(configNode));
			buffer.append("\n");
			writer.write(configNode.toString());
		}
		writer.write("\n\n");
	}
	if (buffer.length() > 0) {
		String str = buffer.toString();
		return new StringBuffer(str.substring(0, str.length() - 1));
	}
	return buffer;
}
 
Example 7
Project: incubator-netbeans   File: EditableManifest.java   Source Code and License Vote up 5 votes
public void write(Writer w) throws IOException {
    // translating all newlines to correct format,
    // see SingleModulePropertiesTest#testThatManifestFormattingIsNotMessedUp_61248
    String output = NEWLINE.matcher(text).replaceAll(RET);
    w.write(output);
    newline(w);
}
 
Example 8
Project: hadoop   File: TestUserDefinedCounters.java   Source Code and License Vote up 5 votes
private void cleanAndCreateInput(FileSystem fs) throws IOException {
  fs.delete(INPUT_DIR, true);
  fs.delete(OUTPUT_DIR, true);

  OutputStream os = fs.create(INPUT_FILE);

  Writer wr = new OutputStreamWriter(os);
  wr.write("hello1\n");
  wr.write("hello2\n");
  wr.write("hello3\n");
  wr.write("hello4\n");
  wr.close();
}
 
Example 9
Project: greycat-idea-plugin   File: PrettyPrinter.java   Source Code and License Vote up 5 votes
private void printEnum(Writer sw, EEnum en) throws IOException {
    sw.write("\n");
    sw.write("enum " + fqn(en) + " {\n");
    for (EEnumLiteral literal : en.getELiterals()) {
        sw.append("    " + literal.getLiteral() + "\n");
    }
    sw.write("}\n");
}
 
Example 10
Project: framework   File: StreamUtil.java   Source Code and License Vote up 5 votes
public static void io(Reader in, Writer out, int bufferSize) throws IOException {
	if (bufferSize == -1) {
		bufferSize = DEFAULT_BUFFER_SIZE >> 1;
	}

	char[] buffer = new char[bufferSize];
	int amount;

	while ((amount = in.read(buffer)) >= 0) {
		out.write(buffer, 0, amount);
	}
}
 
Example 11
Project: boohee_v5.6   File: ButterKnifeProcessor.java   Source Code and License Vote up 5 votes
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
    for (Entry<TypeElement, ViewInjector> entry : findAndParseTargets(env).entrySet()) {
        TypeElement typeElement = (TypeElement) entry.getKey();
        ViewInjector viewInjector = (ViewInjector) entry.getValue();
        try {
            Writer writer = this.filer.createSourceFile(viewInjector.getFqcn(), new Element[]{typeElement}).openWriter();
            writer.write(viewInjector.brewJava());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            error(typeElement, "Unable to write injector for type %s: %s", typeElement, e.getMessage());
        }
    }
    return true;
}
 
Example 12
Project: AndroidWeb   File: Processor.java   Source Code and License Vote up 4 votes
public void render(String templateFile, Map<String, Object> bindings, Writer out)
        throws IOException {
    out.write(render(templateFile, bindings));
}
 
Example 13
Project: illuminati   File: IlluminatiProcessor.java   Source Code and License Vote up 4 votes
@Override public boolean process(Set<? extends TypeElement> typeElements, RoundEnvironment env)  {
    this.messager.printMessage(Kind.WARNING, "start illuminati compile");
    outerloop:
    for (TypeElement typeElement : typeElements) {
        for (Element element : env.getElementsAnnotatedWith(typeElement)) {
            Illuminati illuminati = element.getAnnotation(Illuminati.class);

            if (illuminati != null) {
                if (element.getKind() != ElementKind.CLASS && element.getKind() != ElementKind.METHOD) {
                    this.messager.printMessage(Kind.ERROR, "The class %s is not class or method."+ element.getSimpleName());
                    break outerloop;
                }

                final PackageElement pkg = processingEnv.getElementUtils().getPackageOf(element);

                if (pkg == null) {
                    // Exception
                    this.messager.printMessage(Kind.ERROR, "Sorry, basePackage is wrong in properties read process.");
                    break outerloop;
                }

                if(this.setGeneratedIlluminatiTemplate(pkg.toString())) {
                    try {
                        final JavaFileObject javaFile = this.filer.createSourceFile("IlluminatiPointcutGenerated");
                        final Writer writer = javaFile.openWriter();

                        if (writer != null) {
                            writer.write(this.generatedIlluminatiTemplate);
                            writer.close();
                            this.messager.printMessage(Kind.NOTE, "generate source code!!");
                        } else {
                            this.messager.printMessage(Kind.ERROR, "Sorry, something is wrong in writer 'IlluminatiPointcutGenerated.java' process.");
                        }

                        // IlluminatiPointcutGenerated must exists only one on classloader.
                        break outerloop;
                    } catch (IOException e) {
                        this.messager.printMessage(Kind.ERROR, "Sorry, something is wrong in generated 'IlluminatiPointcutGenerated.java' process.");
                        break outerloop;
                    }
                }
            }
        }
    }

    return true;
}
 
Example 14
Project: quorrabot   File: JSONObject.java   Source Code and License Vote up 4 votes
public static Writer quote(String string, Writer w) throws IOException {
    if (string == null || string.length() == 0) {
        w.write("\"\"");
        return w;
    }

    char b;
    char c = 0;
    String hhhh;
    int i;
    int len = string.length();

    w.write('"');
    for (i = 0; i < len; i += 1) {
        b = c;
        c = string.charAt(i);
        switch (c) {
            case '\\':
            case '"':
                w.write('\\');
                w.write(c);
                break;
            case '/':
                if (b == '<') {
                    w.write('\\');
                }
                w.write(c);
                break;
            case '\b':
                w.write("\\b");
                break;
            case '\t':
                w.write("\\t");
                break;
            case '\n':
                w.write("\\n");
                break;
            case '\f':
                w.write("\\f");
                break;
            case '\r':
                w.write("\\r");
                break;
            default:
                if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
                        || (c >= '\u2000' && c < '\u2100')) {
                    w.write("\\u");
                    hhhh = Integer.toHexString(c);
                    w.write("0000", 0, 4 - hhhh.length());
                    w.write(hhhh);
                } else {
                    w.write(c);
                }
        }
    }
    w.write('"');
    return w;
}
 
Example 15
Project: OpenJSharp   File: JNIWriter.java   Source Code and License Vote up 4 votes
protected void println(Writer out, String text) throws IOException {
    out.write(text);
    out.write(lineSep);
}
 
Example 16
Project: CPG   File: JSONObject.java   Source Code and License Vote up 4 votes
public static Writer quote(String string, Writer w) throws IOException {
    if (string == null || string.length() == 0) {
        w.write("\"\"");
        return w;
    }

    char b;
    char c = 0;
    String hhhh;
    int i;
    int len = string.length();

    w.write('"');
    for (i = 0; i < len; i += 1) {
        b = c;
        c = string.charAt(i);
        switch (c) {
        case '\\':
        case '"':
            w.write('\\');
            w.write(c);
            break;
        case '/':
            if (b == '<') {
                w.write('\\');
            }
            w.write(c);
            break;
        case '\b':
            w.write("\\b");
            break;
        case '\t':
            w.write("\\t");
            break;
        case '\n':
            w.write("\\n");
            break;
        case '\f':
            w.write("\\f");
            break;
        case '\r':
            w.write("\\r");
            break;
        default:
            if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
                    || (c >= '\u2000' && c < '\u2100')) {
                w.write("\\u");
                hhhh = Integer.toHexString(c);
                w.write("0000", 0, 4 - hhhh.length());
                w.write(hhhh);
            } else {
                w.write(c);
            }
        }
    }
    w.write('"');
    return w;
}
 
Example 17
Project: yacy_grid_mcp   File: JSONObject.java   Source Code and License Vote up 4 votes
static final Writer writeValue(Writer writer, Object value,
        int indentFactor, int indent) throws JSONException, IOException {
    if (value == null || value.equals(null)) {
        writer.write("null");
    } else if (value instanceof JSONString) {
        Object o;
        try {
            o = ((JSONString) value).toJSONString();
        } catch (Exception e) {
            throw new JSONException(e);
        }
        writer.write(o != null ? o.toString() : quote(value.toString()));
    } else if (value instanceof Number) {
        // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary
        final String numberAsString = numberToString((Number) value);
        try {
            // Use the BigDecimal constructor for it's parser to validate the format.
            @SuppressWarnings("unused")
            BigDecimal testNum = new BigDecimal(numberAsString);
            // Close enough to a JSON number that we will use it unquoted
            writer.write(numberAsString);
        } catch (NumberFormatException ex){
            // The Number value is not a valid JSON number.
            // Instead we will quote it as a string
            quote(numberAsString, writer);
        }
    } else if (value instanceof Boolean) {
        writer.write(value.toString());
    } else if (value instanceof Enum<?>) {
        writer.write(quote(((Enum<?>)value).name()));
    } else if (value instanceof JSONObject) {
        ((JSONObject) value).write(writer, indentFactor, indent);
    } else if (value instanceof JSONArray) {
        ((JSONArray) value).write(writer, indentFactor, indent);
    } else if (value instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) value;
        new JSONObject(map).write(writer, indentFactor, indent);
    } else if (value instanceof Collection) {
        Collection<?> coll = (Collection<?>) value;
        new JSONArray(coll).write(writer, indentFactor, indent);
    } else if (value.getClass().isArray()) {
        new JSONArray(value).write(writer, indentFactor, indent);
    } else {
        quote(value.toString(), writer);
    }
    return writer;
}
 
Example 18
Project: FlarumSDK   File: JSONObject.java   Source Code and License Vote up 4 votes
public static Writer quote(String string, Writer w) throws IOException {
    if (string == null || string.length() == 0) {
        w.write("\"\"");
        return w;
    }

    char b;
    char c = 0;
    String hhhh;
    int i;
    int len = string.length();

    w.write('"');
    for (i = 0; i < len; i += 1) {
        b = c;
        c = string.charAt(i);
        switch (c) {
        case '\\':
        case '"':
            w.write('\\');
            w.write(c);
            break;
        case '/':
            if (b == '<') {
                w.write('\\');
            }
            w.write(c);
            break;
        case '\b':
            w.write("\\b");
            break;
        case '\t':
            w.write("\\t");
            break;
        case '\n':
            w.write("\\n");
            break;
        case '\f':
            w.write("\\f");
            break;
        case '\r':
            w.write("\\r");
            break;
        default:
            if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
                    || (c >= '\u2000' && c < '\u2100')) {
                w.write("\\u");
                hhhh = Integer.toHexString(c);
                w.write("0000", 0, 4 - hhhh.length());
                w.write(hhhh);
            } else {
                w.write(c);
            }
        }
    }
    w.write('"');
    return w;
}
 
Example 19
Project: JGame   File: Save.java   Source Code and License Vote up 3 votes
public void SaveMap() throws IOException {
	Writer writer = new FileWriter(System.getProperty("user.dir") + "/saves/save.txt");

	try {
		writer.write(Integer.toString(this.seed));
	} finally {
		writer.close();

	}

	BufferedReader br = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/saves/save.txt"));

	try {

		String line;

		while ((line = br.readLine()) != null) {
			c = line;
			System.out.println(c);
		}
	} finally {

		br.close();

	}

}
 
Example 20
Project: Moenagade   File: IOUtils.java   Source Code and License Vote up 3 votes
/**
 * Writes chars from a <code>StringBuffer</code> to a <code>Writer</code>.
 * 
 * @param data  the <code>StringBuffer</code> to write, null ignored
 * @param output  the <code>Writer</code> to write to
 * @throws NullPointerException if output is null
 * @throws IOException if an I/O error occurs
 * @since Commons IO 1.1
 * @deprecated replaced by write(CharSequence, Writer)
 */
@Deprecated
public static void write(StringBuffer data, Writer output)
        throws IOException {
    if (data != null) {
        output.write(data.toString());
    }
}