下面列出了java.io.Writer#flush ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private File createSampleFile()
throws IOException
{
File file = File.createTempFile("obs-android-sdk-", ".txt");
file.deleteOnExit();
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
for (int i = 0; i < 1000000; i++)
{
writer.write(UUID.randomUUID() + "\n\n");
writer.write(UUID.randomUUID() + "\n\n");
}
writer.flush();
writer.close();
return file;
}
@Nullable
public static File buildCrashLog(@NonNull Context context, @NonNull String stackTrace) {
try {
if (stackTrace.length() == 0) return null;
File crashLog = new File(context.getCacheDir(), CRASHLOG);
String deviceInfo = DeviceHelper.getDeviceInfoForCrashReport(context);
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(crashLog), "UTF8"));
out.append(deviceInfo).append(stackTrace);
out.flush();
out.close();
return crashLog;
} catch (Exception e) {
LogUtil.e(Log.getStackTraceString(e));
return null;
}
}
/**
* Allows this writer to be used within the closure, ensuring that it
* is flushed and closed before this method returns.
*
* @param writer the writer which is used and then closed
* @param closure the closure that the writer is passed into
* @return the value returned by the closure
* @throws IOException if an IOException occurs.
* @since 1.5.2
*/
public static <T> T withWriter(Writer writer, @ClosureParams(FirstParam.class) Closure<T> closure) throws IOException {
try {
T result = closure.call(writer);
try {
writer.flush();
} catch (IOException e) {
// try to continue even in case of error
}
Writer temp = writer;
writer = null;
temp.close();
return result;
} finally {
closeWithWarning(writer);
}
}
/**
* Processes the template
*
* @param varMap variable map
* @param out the writer to output the text to.
*/
@Override
public void process(Map<String, String> varMap, Writer out)
{
try
{
if (templateText == null)
{
templateText = Utils.readFileIntoString(input);
}
String replacedString = replace(varMap);
out.write(replacedString);
out.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
static void exportAll(String filename, boolean withHeader, String db_passwd) throws IOException{
Database db = openDatabase( filename, db_passwd ) ;
try{
for(String tableName : db.getTableNames()){
String csvName = tableName + ".csv";
Writer csv = new FileWriter(csvName);
try{
System.out.println(String.format("Exporting '%s' to %s/%s",
tableName, System.getProperty("user.dir"), csvName));
int rows = export(db, tableName, csv, withHeader);
System.out.println(String.format("%d rows exported", rows));
}finally{
try{
csv.flush();
csv.close();
}catch(IOException ex){}
}
}
}finally{
db.close();
}
}
@Transactional(readOnly = true)
public void index(CmsSite site, String tpl, Map<String, Object> data)
throws IOException, TemplateException {
long time = System.currentTimeMillis();
File f = new File(getIndexPath(site));
File parent = f.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
Writer out = null;
try {
// FileWriter不能指定编码确实是个问题,只能用这个代替了。
out = new OutputStreamWriter(new FileOutputStream(f), UTF8);
Template template = conf.getTemplate(tpl);
template.process(data, out);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
time = System.currentTimeMillis() - time;
log.info("create index page, in {} ms", time);
}
public StreamingOutput getRepourLogsForBuild(String repourLog) {
if (repourLog == null)
return null;
return outputStream -> {
Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write(repourLog);
writer.flush();
};
}
@Override
public void writeTo(List<AppointmentDTO> t, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out)
throws IOException
{
Writer writer = new OutputStreamWriter(out, UTF_8);
JSONArray rr = new JSONArray();
for (AppointmentDTO dto : t) {
rr.put(AppointmentParamConverter.json(dto));
}
writer.write(new JSONObject().put(ROOT, rr).toString());
writer.flush();
}
@Override
public boolean add(T log) {
boolean ret = false;
String msg = MiscUtil.stringify(log);
if(msg.contains(MiscUtil.LINE_SEPARATOR)) {
msg = msg.replace(MiscUtil.LINE_SEPARATOR, MiscUtil.ESCAPE_STR + MiscUtil.LINE_SEPARATOR);
}
synchronized(this) {
checkFileStatus();
Writer writer = mWriter;
if(writer != null) {
try {
writer.write(msg + MiscUtil.LINE_SEPARATOR);
if(mFileBufferSizeBytes == 0) {
writer.flush();
}
ret = true;
} catch(IOException excp) {
mLogger.warn("LocalFileLogBuffer.add(): write failed", excp);
closeFile();
}
}
}
return ret;
}
/**
* Renders an HTTP response that will cause the browser to POST the specified values to an url.
* @param url the url where to perform the POST.
* @param response the {@link HttpServletResponse}.
* @param values the values to include in the POST.
* @throws IOException thrown if an IO error occurs.
*/
public static void postUsingBrowser(
String url, HttpServletResponse response, Map<String, String> values) throws IOException {
response.setContentType("text/html");
@SuppressWarnings("resource")
Writer writer = response.getWriter();
writer.write(
"<html><head></head><body><form id='TheForm' action='"
+ StringEscapeUtils.escapeHtml(url)
+ "' method='POST'>");
for (String key : values.keySet()) {
String encodedKey = StringEscapeUtils.escapeHtml(key);
String encodedValue = StringEscapeUtils.escapeHtml(values.get(key));
writer.write(
"<input type='hidden' id='"
+ encodedKey
+ "' name='"
+ encodedKey
+ "' value='"
+ encodedValue
+ "'/>");
}
writer.write(
"</form><script type='text/javascript'>document.getElementById('TheForm').submit();</script></body></html>");
writer.flush();
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
}
/**
* flush Writer
*
* @param br
*/
public static void flushWriter(Writer wr) {
if (wr != null) {
try {
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
*/
private void createManifestEntry(String mimetype) throws IOException
{
ExportZipEntry manifestEntry = createEntry("META-INF/manifest.xml");
Writer manifestWriter = null;
try
{
manifestWriter = manifestEntry.getWriter();
manifestWriter.write(PROLOG);
manifestWriter.write("<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n");
manifestWriter.write("<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument." + mimetype + "\" manifest:full-path=\"/\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"application/vnd.sun.xml.ui.configuration\" manifest:full-path=\"Configurations2/\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"\" manifest:full-path=\"Pictures/\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"\" manifest:full-path=\"Thumbnails/thumbnail.png\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"\" manifest:full-path=\"Thumbnails/\"/>\n");
manifestWriter.write(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"settings.xml\"/>\n");
manifestWriter.write("</manifest:manifest>\n");
manifestWriter.flush();
}
finally
{
if (manifestWriter != null)
{
try
{
manifestWriter.close();
}
catch (IOException e)
{
}
}
}
}
@Override
public void writeTo(JSONStreamAware jsonStreamAware, Class<?> aClass, Type type, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> stringObjectMultivaluedMap,
OutputStream outputStream) throws IOException, WebApplicationException {
Writer writer = new OutputStreamWriter(outputStream, Charsets.UTF_8);
jsonStreamAware.writeJSONString(writer);
writer.write(ENTER);
writer.flush();
}
/** Write the project as XML.
*
* @param project
* @param writer
* @param options
* */
public void writeXMLTo(final Project project, final Writer writer, final XMLOptions options) throws Exception {
StringBuilder sb_header = new StringBuilder(30000).append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<!DOCTYPE ").append(project.getDocType()).append(" [\n");
project.exportDTD(sb_header, new HashSet<String>(), "\t");
sb_header.append("] >\n\n");
writer.write(sb_header.toString());
sb_header = null;
project.exportXML(writer, "", options);
writer.flush(); // make sure all buffered chars are written
}
/**
* Runs the test.
*/
public void testIncludeEventHandling ()
throws Exception
{
Template template1 = RuntimeSingleton.getTemplate(
getFileName(null, "test1", TMPL_FILE_EXT));
Template template2 = RuntimeSingleton.getTemplate(
getFileName(null, "subdir/test2", TMPL_FILE_EXT));
Template template3 = RuntimeSingleton.getTemplate(
getFileName(null, "test3", TMPL_FILE_EXT));
FileOutputStream fos1 =
new FileOutputStream (
getFileName(RESULTS_DIR, "test1", RESULT_FILE_EXT));
FileOutputStream fos2 =
new FileOutputStream (
getFileName(RESULTS_DIR, "test2", RESULT_FILE_EXT));
FileOutputStream fos3 =
new FileOutputStream (
getFileName(RESULTS_DIR, "test3", RESULT_FILE_EXT));
Writer writer1 = new BufferedWriter(new OutputStreamWriter(fos1));
Writer writer2 = new BufferedWriter(new OutputStreamWriter(fos2));
Writer writer3 = new BufferedWriter(new OutputStreamWriter(fos3));
/*
* lets make a Context and add the event cartridge
*/
Context context = new VelocityContext();
/*
* Now make an event cartridge, register the
* input event handler and attach it to the
* Context
*/
EventCartridge ec = new EventCartridge();
ec.addEventHandler(this);
ec.attachToContext( context );
// BEHAVIOR A: pass through #input and #parse with no change
EventHandlerBehavior = PASS_THROUGH;
template1.merge(context, writer1);
writer1.flush();
writer1.close();
// BEHAVIOR B: pass through #input and #parse with using a relative path
EventHandlerBehavior = RELATIVE_PATH;
template2.merge(context, writer2);
writer2.flush();
writer2.close();
// BEHAVIOR C: refuse to pass through #input and #parse
EventHandlerBehavior = BLOCK;
template3.merge(context, writer3);
writer3.flush();
writer3.close();
if (!isMatch(RESULTS_DIR, COMPARE_DIR, "test1",
RESULT_FILE_EXT, CMP_FILE_EXT) ||
!isMatch(RESULTS_DIR, COMPARE_DIR, "test2",
RESULT_FILE_EXT, CMP_FILE_EXT) ||
!isMatch(RESULTS_DIR, COMPARE_DIR, "test3",
RESULT_FILE_EXT, CMP_FILE_EXT)
)
{
fail("Output incorrect.");
}
}
/**
* Runs the test.
*/
public void testClasspathResource ()
throws Exception
{
/*
* lets ensure the results directory exists
*/
assureResultsDirectoryExists(RESULTS_DIR);
Template template1 = RuntimeSingleton.getTemplate("/includeevent/test1-cp." + TMPL_FILE_EXT);
// Uncomment when http://jira.codehaus.org/browse/MPTEST-57 has been resolved
// Template template2 = RuntimeSingleton.getTemplate(
// getFileName(null, "template/test2", TMPL_FILE_EXT));
FileOutputStream fos1 =
new FileOutputStream (
getFileName(RESULTS_DIR, "test1", RESULT_FILE_EXT));
// Uncomment when http://jira.codehaus.org/browse/MPTEST-57 has been resolved
// FileOutputStream fos2 =
// new FileOutputStream (
// getFileName(RESULTS_DIR, "test2", RESULT_FILE_EXT));
Writer writer1 = new BufferedWriter(new OutputStreamWriter(fos1));
// Uncomment when http://jira.codehaus.org/browse/MPTEST-57 has been resolved
// Writer writer2 = new BufferedWriter(new OutputStreamWriter(fos2));
/*
* put the Vector into the context, and merge both
*/
VelocityContext context = new VelocityContext();
template1.merge(context, writer1);
writer1.flush();
writer1.close();
// Uncomment when http://jira.codehaus.org/browse/MPTEST-57 has been resolved
// template2.merge(context, writer2);
// writer2.flush();
// writer2.close();
if (!isMatch(RESULTS_DIR,COMPARE_DIR,"test1",RESULT_FILE_EXT,CMP_FILE_EXT)
// Uncomment when http://jira.codehaus.org/browse/MPTEST-57 has been resolved
// || !isMatch(RESULTS_DIR,COMPARE_DIR,"test2",RESULT_FILE_EXT,CMP_FILE_EXT)
)
{
fail("Output is incorrect!");
}
}
protected void exportReportToStream(Writer writer) throws JRException, IOException
{
version = getPropertiesUtil().getProperty(jasperPrint, JRXmlBaseWriter.PROPERTY_REPORT_VERSION);
xmlWriter = new JRXmlWriteHelper(writer);
xmlWriter.writeProlog(getExporterOutput().getEncoding());
xmlWriter.startElement(JRXmlConstants.ELEMENT_jasperPrint, getNamespace());
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, jasperPrint.getName());
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_pageWidth, jasperPrint.getPageWidth());
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_pageHeight, jasperPrint.getPageHeight());
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_topMargin, jasperPrint.getTopMargin());
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_leftMargin, jasperPrint.getLeftMargin());
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_bottomMargin, jasperPrint.getBottomMargin());
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_rightMargin, jasperPrint.getRightMargin());
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_orientation, jasperPrint.getOrientationValue(), OrientationEnum.PORTRAIT);
xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_formatFactoryClass, jasperPrint.getFormatFactoryClass());
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_locale, jasperPrint.getLocaleCode());
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_timezone, jasperPrint.getTimeZoneId());
setCurrentExporterInputItem(exporterInput.getItems().get(0));
List<JRPrintPage> pages = jasperPrint.getPages();
PageRange pageRange = getPageRange();
int startPageIndex = (pageRange == null || pageRange.getStartPageIndex() == null) ? 0 : pageRange.getStartPageIndex();
int endPageIndex = (pageRange == null || pageRange.getEndPageIndex() == null) ? (pages.size() - 1) : pageRange.getEndPageIndex();
//FIXME this leads to property duplication if a JasperPrint is loaded
//from a *.jrpxml and exported back to xml
xmlWriter.startElement(JRXmlConstants.ELEMENT_property);
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, PROPERTY_START_PAGE_INDEX);
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_value, String.valueOf(startPageIndex));
xmlWriter.closeElement();
xmlWriter.startElement(JRXmlConstants.ELEMENT_property);
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, PROPERTY_END_PAGE_INDEX);
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_value, String.valueOf(endPageIndex));
xmlWriter.closeElement();
xmlWriter.startElement(JRXmlConstants.ELEMENT_property); //FIXME make this configurable?
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, PROPERTY_PAGE_COUNT);
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_value, jasperPrint.getPages() == null ? null : String.valueOf(jasperPrint.getPages().size()));
xmlWriter.closeElement();
exportProperties(jasperPrint);
JROrigin[] origins = jasperPrint.getOrigins();
if (origins != null && origins.length > 0)
{
for(int i = 0; i < origins.length; i++)
{
exportOrigin(origins[i]);
}
}
JRStyle[] styles = jasperPrint.getStyles();
if (styles != null && styles.length > 0)
{
for(int i = 0; i < styles.length; i++)
{
stylesMap.put(styles[i].getName(), styles[i]);
exportStyle(styles[i]);
}
}
exportBookmarks(jasperPrint.getBookmarks());
PrintParts parts = jasperPrint.getParts();
if (parts != null && parts.hasParts())
{
for (Iterator<Map.Entry<Integer, PrintPart>> it = parts.partsIterator(); it.hasNext();)
{
Map.Entry<Integer, PrintPart> partsEntry = it.next();
/* */
exportPart(partsEntry.getKey(), partsEntry.getValue());
}
}
if (pages != null && pages.size() > 0)
{
JRPrintPage page = null;
for(int i = startPageIndex; i <= endPageIndex; i++)
{
if (Thread.interrupted())
{
throw new ExportInterruptedException();
}
page = pages.get(i);
/* */
exportPage(page);
}
}
xmlWriter.closeElement();
writer.flush();
}
/**
* Serializes a Document Type Node.
*
* @param node The Docuemnt Type Node to serialize
* @param bStart Invoked at the start or end of node. Default true.
*/
protected void serializeDocType(DocumentType node, boolean bStart)
throws SAXException {
// The DocType and internalSubset can not be modified in DOM and is
// considered to be well-formed as the outcome of successful parsing.
String docTypeName = node.getNodeName();
String publicId = node.getPublicId();
String systemId = node.getSystemId();
String internalSubset = node.getInternalSubset();
//DocumentType nodes are never passed to the filter
if (internalSubset != null && !"".equals(internalSubset)) {
if (bStart) {
try {
// The Serializer does not provide a way to write out the
// DOCTYPE internal subset via an event call, so we write it
// out here.
Writer writer = fSerializer.getWriter();
StringBuffer dtd = new StringBuffer();
dtd.append("<!DOCTYPE ");
dtd.append(docTypeName);
if (null != publicId) {
dtd.append(" PUBLIC \"");
dtd.append(publicId);
dtd.append('\"');
}
if (null != systemId) {
if (null == publicId) {
dtd.append(" SYSTEM \"");
} else {
dtd.append(" \"");
}
dtd.append(systemId);
dtd.append('\"');
}
dtd.append(" [ ");
dtd.append(fNewLine);
dtd.append(internalSubset);
dtd.append("]>");
dtd.append(fNewLine);
writer.write(dtd.toString());
writer.flush();
} catch (IOException e) {
throw new SAXException(Utils.messages.createMessage(
MsgKey.ER_WRITING_INTERNAL_SUBSET, null), e);
}
} // else if !bStart do nothing
} else {
if (bStart) {
if (fLexicalHandler != null) {
fLexicalHandler.startDTD(docTypeName, publicId, systemId);
}
} else {
if (fLexicalHandler != null) {
fLexicalHandler.endDTD();
}
}
}
}
protected void measureNow(String[] args)
throws IOException {
this.path = args[1];
String bn_name = args[2];
Writer wr = RandomStuff.getWriter(
RandomStuff.f("%s/res/%s", this.path, bn_name));
RandomStuff.wf(wr, "### %s ###\n", bn_name);
for (int p = 0; p < this.percs.length; p++) {
int per = this.percs[p];
RandomStuff.wf(wr, "\[email protected]@@ %d \n", per);
for (String classi : this.classifiers) {
RandomStuff.wf(wr, "\n### %s \n", classi);
for (String m : new String[] {
"orig", "sem", "rfsrc", "missing" }) {
double mae = 0.0D;
double auc = 0.0D;
for (int f = 1; f <= this.max_fold; f++) {
String out = RandomStuff.f(
"%s/work/%s/fold%d/%d/eval/%s/%s-out", this.path,
bn_name, f, per, classi, m);
BufferedReader br = RandomStuff.getReader(out);
boolean ok = false;
String ll;
while ((ll = br.readLine()) != null) {
if (ll.contains("Error on test data")) {
ok = true;
}
if ((ok) && (ll.contains("Mean absolute error"))) {
mae += last(ll, 3);
}
if ((ok) && (ll.contains("Weighted Avg."))) {
auc += last(ll, 8);
}
}
}
RandomStuff.wf(wr, "%10s, auc: %4.4f, mae: %4.4f \n", m,
auc / this.max_fold, mae / this.max_fold);
wr.flush();
}
}
}
wr.close();
}
/**
* parses the given command and executes it
*
* @param np
* @throws java.io.IOException
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("list assignmentsToLevels");
final String fileName;
if (np.peekMatchIgnoreCase("outFile")) {
np.matchIgnoreCase("outFile=");
fileName = np.getWordFileNamePunctuation();
} else
fileName = null;
np.matchIgnoreCase(";");
// use -3 for leaves, -2 and -1 for no hits and unassigned
final SortedMap<Integer, Float> level2count = new TreeMap<>();
level2count.put(-3, 0f);
level2count.put(-2, 0f);
level2count.put(-1, 0f);
final SortedMap<String, Float> rank2count = new TreeMap<>();
final PhyloTree tree = getDir().getMainViewer().getTree();
listAssignmentsRec(tree, tree.getRoot(), 0, level2count, rank2count);
final Writer w = new BufferedWriter(fileName == null ? new OutputStreamWriter(System.out) : new FileWriter(fileName));
int count = 0;
try {
w.write("########## Begin of level-to-assignment listing for file: " + getDir().getDocument().getMeganFile().getName() + "\n");
w.write("To leaves: " + level2count.get(-3) + "\n");
w.write("Unassigned: " + level2count.get(-2) + "\n");
w.write("No hits: " + level2count.get(-1) + "\n");
w.write("Assignments to levels (distance from root):\n");
count += 5;
for (int level : level2count.keySet()) {
if (level >= 0) {
w.write(level + "\t" + level2count.get(level) + "\n");
count++;
}
}
w.write("Assignments to taxonomic ranks (where known):\n");
count++;
for (String rank : TaxonomicLevels.getAllNames()) {
if (rank2count.get(rank) != null) {
w.write(rank + "\t" + rank2count.get(rank) + "\n");
count++;
}
}
w.write("########## End of level-to-assignment listing\n");
count++;
} finally {
if (fileName != null)
w.close();
else
w.flush();
}
if (fileName != null && count > 0)
NotificationsInSwing.showInformation(getViewer().getFrame(), "Lines written to file: " + count);
}