下面列出了java.io.OutputStreamWriter#flush ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void handle(HttpExchange t) throws IOException {
String query = t.getRequestURI().getRawQuery();
ByteArrayOutputStream response = this.response.get();
response.reset();
OutputStreamWriter osw = new OutputStreamWriter(response);
TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query)));
osw.flush();
osw.close();
response.flush();
response.close();
t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
if (shouldUseCompression(t)) {
t.getResponseHeaders().set("Content-Encoding", "gzip");
t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
response.writeTo(os);
os.finish();
} else {
t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
response.writeTo(t.getResponseBody());
}
t.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
OutputStreamWriter outputWriter = ServletUtils.prepareResponse(response);
StringBuilder output = new StringBuilder();
output.append("<response>");
output.append(processPostQuery(request));
output.append("</response>");
if (_engine.enginePersistenceFailure())
{
_log.fatal("************************************************************");
_log.fatal("A failure has occurred whilst persisting workflow state to the");
_log.fatal("database. Check the status of the database connection defined");
_log.fatal("for the YAWL service, and restart the YAWL web application.");
_log.fatal("Further information may be found within the Tomcat log files.");
_log.fatal("************************************************************");
response.sendError(500, "Database persistence failure detected");
}
outputWriter.write(output.toString());
outputWriter.flush();
outputWriter.close();
//todo find out how to provide a meaningful 500 message in the format of a fault message.
}
@Override
public void print(UnknownFieldSet fields, OutputStream output, Charset cs)
throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(output, cs);
print(fields, writer);
writer.flush();
}
public static void writeAll(OutputStream out, CharSequence content) throws IOException
{
OutputStreamWriter w = new OutputStreamWriter(out);
try
{
w.append(content);
}
finally
{
w.flush();
}
}
@Test
public void testWriteChar() throws IOException {
// 1、创建字符输出流
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw2.txt"));
// 2、写数据
// public void write(int c):写一个字符
// osw.write('a');
// osw.write(97);
// 为什么数据没有进去呢?
// 原因是:字符 = 2字节
// 文件中数据存储的基本单位是字节。
// void flush()
// public void write(char[] cbuf):写一个字符数组
// char[] chs = {'a','b','c','d','e'};
// osw.write(chs);
// public void write(char[] cbuf,int off,int len):写一个字符数组的一部分
// osw.write(chs,1,3);
// public void write(String str):写一个字符串
// osw.write("我爱林青霞");
// public void write(String str,int off,int len):写一个字符串的一部分
osw.write("我爱林青霞", 2, 3);
// 刷新缓冲区
osw.flush();
// osw.write("我爱林青霞", 2, 3);
// 3、释放资源
osw.close();
// java.io.IOException: Stream closed
// osw.write("我爱林青霞", 2, 3);
}
private void a(String str, String str2) {
try {
if (this.d != null) {
str = str + "." + this.d;
}
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.c.openFileOutput(str, 0), Charset.forName("UTF-8"));
outputStreamWriter.write(str2);
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Writes a content object into a set of output files. The content is one of {@link Doc}, {@link
* String} or {@code byte[]}.
*/
public static void writeFiles(Map<String, ?> content, String baseName) throws IOException {
for (Map.Entry<String, ?> entry : content.entrySet()) {
File outputFile =
Strings.isNullOrEmpty(baseName)
? new File(entry.getKey())
: new File(baseName, entry.getKey());
outputFile.getParentFile().mkdirs();
OutputStream outputStream = new FileOutputStream(outputFile);
OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
try {
Object value = entry.getValue();
if (value instanceof Doc) {
writer.write(((Doc) value).prettyPrint());
writer.flush();
} else if (value instanceof String) {
writer.write((String) value);
writer.flush();
} else if (value instanceof byte[]) {
outputStream.write((byte[]) value);
outputStream.flush();
} else {
throw new IllegalArgumentException("Expected one of Doc, String, or byte[]");
}
} finally {
writer.close();
}
}
}
public static void stringToFile(String content, File file) throws IOException {
OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
sw.write('\ufeff'); // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
sw.write(content);
sw.flush();
sw.close();
}
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
CommandSetProperty spCommand = (CommandSetProperty) command;
StringBuilder data = new StringBuilder();
data.append("values=");
data.append(spCommand.property);
data.append("=\"");
data.append(spCommand.value);
data.append("\"");
wr.write(data.toString());
wr.flush();
wr.close();
}
public FileLog() {
if (!BuildVars.DEBUG_VERSION) {
return;
}
dateFormat = FastDateFormat.getInstance("dd_MM_yyyy_HH_mm_ss", Locale.US);
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
if (sdCard == null) {
return;
}
File dir = new File(sdCard.getAbsolutePath() + "/logs");
if (dir == null) {
return;
}
dir.mkdirs();
currentFile = new File(dir, dateFormat.format(System.currentTimeMillis()) + ".txt");
if (currentFile == null) {
return;
}
try {
currentFile.createNewFile();
FileOutputStream stream = new FileOutputStream(currentFile);
streamWriter = new OutputStreamWriter(stream);
streamWriter.write("-----start log " + dateFormat.format(System.currentTimeMillis()) + "-----\n");
streamWriter.flush();
logQueue = new DispatchQueue("logQueue");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void compose(OutputStream stream, DataType type, String rootName) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
if (style == OutputStyle.CANONICAL)
json = new JsonCreatorCanonical(osw);
else
json = new JsonCreatorDirect(osw);// use this instead of Gson because this preserves decimal formatting
json.setIndent(style == OutputStyle.PRETTY ? " " : "");
json.beginObject();
composeTypeInner(type);
json.endObject();
json.finish();
osw.flush();
}
/**
* Save this XML into the supplied output stream.
* @param stream the output stream
* @throws IOException on error
*/
public void save(OutputStream stream) throws IOException {
OutputStreamWriter out = new OutputStreamWriter(stream, "UTF-8");
try {
save(out);
} finally {
out.flush();
}
}
/**
* Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
* @throws IOException
*/
@Override
public void compose(OutputStream stream, Resource resource) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
if (style == OutputStyle.CANONICAL)
json = new JsonCreatorCanonical(osw);
else
json = new JsonCreatorDirect(osw); // use this instead of Gson because this preserves decimal formatting
json.setIndent(style == OutputStyle.PRETTY ? " " : "");
json.beginObject();
composeResource(resource);
json.endObject();
json.finish();
osw.flush();
}
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
wr.write("clusterName=" + ((CommandTarget)command).target);
wr.flush();
wr.close();
}
@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
MediaType contentType = outputMessage.getHeaders().getContentType();
if (contentType == null) {
contentType = getDefaultContentType(message);
Assert.state(contentType != null, "No content type");
}
Charset charset = contentType.getCharset();
if (charset == null) {
charset = DEFAULT_CHARSET;
}
if (PROTOBUF.isCompatibleWith(contentType)) {
setProtoHeader(outputMessage, message);
CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
message.writeTo(codedOutputStream);
codedOutputStream.flush();
}
else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
TextFormat.print(message, outputStreamWriter);
outputStreamWriter.flush();
outputMessage.getBody().flush();
}
else if (this.protobufFormatSupport != null) {
this.protobufFormatSupport.print(message, outputMessage.getBody(), contentType, charset);
outputMessage.getBody().flush();
}
}
/**
* Copy data from a reader to a ZipOutputStream.
* @param reader a Reader open on the input dataset/member in the default EBCDIC encoding
* @param zipOutStream the target ZipOutputStram
* @param targetEncoding the target encoding for the ZipOutputStream
* @throws IOException
* @throws UnsupportedEncodingException
*/
private void copyData(Reader reader,
ZipOutputStream zipOutStream,
String targetEncoding)
throws IOException, UnsupportedEncodingException
{
char[] cbuf = new char[BUFSIZE];
int nRead;
// wrap the zipOutputStream in a Writer that encodes to the target encoding
OutputStreamWriter osw = new OutputStreamWriter(zipOutStream, targetEncoding);
while ((nRead = reader.read(cbuf)) != -1) {
osw.write(cbuf, 0, nRead);
}
osw.flush(); // flush any buffered data to the ZipOutputStream
}
/**
* Generate the requsite
*/
public void generateRequsite(String transferId, OutputStream out) throws TransferException
{
log.debug("Generate Requsite for transfer:" + transferId);
try
{
File snapshotFile = getSnapshotFile(transferId);
if (snapshotFile.exists())
{
log.debug("snapshot does exist");
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser parser = saxParserFactory.newSAXParser();
OutputStreamWriter dest = new OutputStreamWriter(out, "UTF-8");
XMLTransferRequsiteWriter writer = new XMLTransferRequsiteWriter(dest);
TransferManifestProcessor processor = manifestProcessorFactory.getRequsiteProcessor(
RepoTransferReceiverImpl.this,
transferId,
writer);
XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);
/**
* Now run the parser
*/
parser.parse(snapshotFile, reader);
/**
* And flush the destination in case any content remains in the writer.
*/
dest.flush();
}
log.debug("Generate Requsite done transfer:" + transferId);
}
catch (Exception ex)
{
if (TransferException.class.isAssignableFrom(ex.getClass()))
{
throw (TransferException) ex;
}
else
{
throw new TransferException(MSG_ERROR_WHILE_GENERATING_REQUISITE, ex);
}
}
}
private static void RunClient(String machineName) {
System.out.println(" Running Client");
try {
SSLSocket ssl_socket;
ssl_socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(machineName, 1501);
// enable certifcate validation:
SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
sslParams.setProtocols(new String[] {"TLSv1.2"});
ssl_socket.setSSLParameters(sslParams);
if (useCompression) {
initiation_command += " compression gzip";
}
initiation_command += "\n";
//send your initiation command
OutputStreamWriter writer = new OutputStreamWriter(ssl_socket.getOutputStream(), "UTF8");
writer.write(initiation_command);
writer.flush();
InputStream inputStream = ssl_socket.getInputStream();
if (useCompression) {
inputStream = new java.util.zip.GZIPInputStream(inputStream);
}
// read messages from FlightAware
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = null;
int limit = 5; //limit number messages for testing
while (limit > 0 && (message = reader.readLine()) != null) {
System.out.println("msg: " + message + "\n");
parse_json(message);
limit--;
}
//done, close everything
writer.close();
reader.close();
inputStream.close();
ssl_socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void encodeApplicationXWWWFormURLEncodedRequest(OutputStream outputStream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
writer.append(encodeQuery());
writer.flush();
}
/**
* Helper method to write a line to a File.
* Extracted to a separate method here to make it a little easier to replace implementations.
*
* @param line The line to write
* @param writer The place to write it
* @throws IOException if an I/O error occurs
*/
private static void write(String line, OutputStreamWriter writer) throws IOException {
synchronized (writer) {
writer.write(line);
writer.flush();
}
}