本文整理匯總了Java中java.io.OutputStreamWriter.write方法的典型用法代碼示例。如果您正苦於以下問題:Java OutputStreamWriter.write方法的具體用法?Java OutputStreamWriter.write怎麽用?Java OutputStreamWriter.write使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.io.OutputStreamWriter
的用法示例。
在下文中一共展示了OutputStreamWriter.write方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: send
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
/**
* Sends the request and returns the response.
*
* @return String
*/
public String send() throws Exception {
URLConnection con = this.url.openConnection();
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(this.body);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = "";
String buffer;
while ((buffer = in.readLine()) != null) {
response += buffer;
}
in.close();
return response;
}
示例2: checkRoot
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
private static void checkRoot() {
sRoot = false;
char[] buff = new char[1024];
try {
Process process = Runtime.getRuntime().exec("su");
OutputStreamWriter output = new OutputStreamWriter(process.getOutputStream());
InputStreamReader input = new InputStreamReader(process.getInputStream());
String testStr = "ROOT_TEST";
output.write("echo " + testStr + "\n");
output.flush();
output.write("exit\n");
output.flush();
process.waitFor();
int count = input.read(buff);
if (count > 0) {
if (new String(buff, 0, count).startsWith(testStr))
sRoot = true;
}
}catch (Exception e){
e.printStackTrace();
}
}
示例3: recover
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
@Override
public void recover(String path,HttpSession session) throws IOException {
initVariableByProperties(); //初始化數據庫連接
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c mysql -h "+ hostIP +" -u "+ userName +" -p"+ password +" --default-character-set=utf8 lemon");
OutputStream outputStream = process.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
ProgressSingleton.put(session.getId()+"Size", new File(path).length()); //記錄文件大小
//文件進度長度
long progress = 0;
String str = null;
OutputStreamWriter writer = new OutputStreamWriter(outputStream,"utf-8");
while((str = br.readLine()) != null){
progress = progress + str.length();
//向單例哈希表寫入進度
ProgressSingleton.put(session.getId()+"Progress", progress);
writer.write(str+"\r\n");
}
ProgressSingleton.remove(session.getId()+"Size");
ProgressSingleton.remove(session.getId()+"Progress");
writer.flush();
outputStream.close();
br.close();
writer.close();
}
示例4: writeIniFile
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
/**
* Writes a .ini file from a set of properties, using UTF-8 encoding.
* The keys are sorted.
* The file should be read back later by {@link #parseIniFile(IAbstractFile, ILogger)}.
*
* @param iniFile The file to generate.
* @param values The properties to place in the ini file.
* @param addEncoding When true, add a property {@link #AVD_INI_ENCODING} indicating the
* encoding used to write the file.
* @throws IOException if {@link FileWriter} fails to open, write or close the file.
*/
private static void writeIniFile(File iniFile, Map<String, String> values, boolean addEncoding)
throws IOException {
Charset charset = Charsets.ISO_8859_1;
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(iniFile), charset);
if (addEncoding) {
// Write down the charset used in case we want to use it later.
writer.write(String.format("%1$s=%2$s\n", AVD_INI_ENCODING, charset.name()));
}
ArrayList<String> keys = new ArrayList<String>(values.keySet());
Collections.sort(keys);
for (String key : keys) {
String value = values.get(key);
writer.write(String.format("%1$s=%2$s\n", key, value));
}
writer.close();
}
示例5: writeXML
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
@Override
public void writeXML(OutputStreamWriter writer) throws IOException {
String fillColor = mVdAttributesMap.get(Svg2Vector.SVG_FILL_COLOR);
String strokeColor = mVdAttributesMap.get(Svg2Vector.SVG_STROKE_COLOR);
logger.log(Level.FINE, "fill color " + fillColor);
boolean emptyFill = fillColor != null && ("none".equals(fillColor) || "#0000000".equals(fillColor));
boolean emptyStroke = strokeColor == null || "none".equals(strokeColor);
boolean emptyPath = mPathData == null;
boolean nothingToDraw = emptyPath || emptyFill && emptyStroke;
if (nothingToDraw) {
return;
}
writer.write(" <path\n");
if (!mVdAttributesMap.containsKey(Svg2Vector.SVG_FILL_COLOR)) {
logger.log(Level.FINE, "ADDING FILL SVG_FILL_COLOR");
writer.write(" android:fillColor=\"#FF000000\"\n");
}
writer.write(" android:pathData=\"" + mPathData + "\"");
writer.write(getAttributeValues(Svg2Vector.presentationMap));
}
示例6: createItemFileWithActiveEditorDrop
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
private FileObject createItemFileWithActiveEditorDrop() throws Exception {
FileObject fo = itemsFolder.createData(ITEM_FILE);
FileLock lock = fo.lock();
try {
OutputStreamWriter writer = new OutputStreamWriter(fo.getOutputStream(lock), "UTF-8");
try {
writer.write("<?xml version='1.0' encoding='UTF-8'?>");
writer.write("<!DOCTYPE editor_palette_item PUBLIC '-//NetBeans//Editor Palette Item 1.0//EN' 'http://www.netbeans.org/dtds/editor-palette-item-1_0.dtd'>");
writer.write("<editor_palette_item version='1.0'>");
writer.write("<class name='" + CLASS_NAME + "' />");
writer.write("<icon16 urlvalue='" + ICON16 + "' />");
writer.write("<icon32 urlvalue='" + ICON32 + "' />");
writer.write("<description localizing-bundle='" + BUNDLE_NAME + "' display-name-key='" + NAME_KEY + "' tooltip-key='" + TOOLTIP_KEY + "' />");
writer.write("</editor_palette_item>");
} finally {
writer.close();
}
} finally {
lock.releaseLock();
}
return fo;
}
示例7: createItemFileWithInLineDescription
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
private FileObject createItemFileWithInLineDescription() throws Exception {
FileObject fo = itemsFolder.createData(ITEM_FILE);
FileLock lock = fo.lock();
try {
OutputStreamWriter writer = new OutputStreamWriter(fo.getOutputStream(lock), "UTF-8");
try {
writer.write("<?xml version='1.0' encoding='UTF-8'?>");
writer.write("<!DOCTYPE editor_palette_item PUBLIC '-//NetBeans//Editor Palette Item 1.1//EN' 'http://www.netbeans.org/dtds/editor-palette-item-1_1.dtd'>");
writer.write("<editor_palette_item version='1.1'>");
writer.write("<body><![CDATA[" + BODY + "]]></body>");
writer.write("<icon16 urlvalue='" + ICON16 + "' />");
writer.write("<icon32 urlvalue='" + ICON32 + "' />");
writer.write("<inline-description> <display-name>"
+NbBundle.getBundle(BUNDLE_NAME).getString(NAME_KEY)+"</display-name> <tooltip>"
+NbBundle.getBundle(BUNDLE_NAME).getString(TOOLTIP_KEY)+"</tooltip> </inline-description>");
writer.write("</editor_palette_item>");
} finally {
writer.close();
}
} finally {
lock.releaseLock();
}
return fo;
}
示例8: Cfg
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
public Cfg() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStreamWriter w = new OutputStreamWriter(os);
w.write("handlers=java.util.logging.FileHandler\n");
w.write(".level=100\n");
w.write("java.util.logging.FileHandler.pattern=" + log.toString().replace('\\', '/') +"\n");
w.close();
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(os.toByteArray()));
}
示例9: handleRequest
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
String apiIntputStream = new Scanner(inputStream).useDelimiter("\\A").next();
JsonNode rootNode = (new ObjectMapper(new JsonFactory())).readTree(apiIntputStream);
String myApiId = rootNode.path("requestContext").path("apiId").asText();
if (myApiId.isEmpty()) { myApiId = "TODO"; } // Not called from API Gateway
final GenericApiGatewayClient client = new GenericApiGatewayClientBuilder()
.withClientConfiguration(new ClientConfiguration())
.withCredentials(new EnvironmentVariableCredentialsProvider())
.withEndpoint("https://" + myApiId + ".execute-api.us-west-2.amazonaws.com") // your API ID
.withRegion(Region.getRegion(Regions.fromName("us-west-2")))
.build();
GenericApiGatewayResponse apiResponse;
ProxyResponse resp;
try {
apiResponse = client.execute( // throws exception for non-2xx response
new GenericApiGatewayRequestBuilder()
.withHttpMethod(HttpMethodName.GET)
.withResourcePath("/Prod/hello").build());
System.out.println("Response: " + apiResponse.getBody());
System.out.println("Status: " + apiResponse.getHttpResponse().getStatusCode());
resp = new ProxyResponse("200", apiResponse.getBody());
} catch (GenericApiGatewayException e) {
System.out.println("Client threw exception " + e);
resp = new ProxyResponse("400", e.getMessage());
}
String responseString = new ObjectMapper(new JsonFactory()).writeValueAsString(resp);
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(responseString);
writer.close();
}
示例10: write
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
public void write(char[] cbuf, int off, int len) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter writer = m_encoding == null
? new OutputStreamWriter(baos)
: new OutputStreamWriter(baos,
m_charset);
writer.write(cbuf, off, len);
writer.close();
m_randomAccessFile.write(baos.toByteArray());
}
示例11: writeToFile
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
private static void writeToFile(OutputStreamWriter stream, long distinctWords, long numWords) throws IOException {
for (long i = 0; i < numWords; i++) {
stream.write(i % distinctWords + "");
if (i % 20 == 0) {
stream.write("\n");
} else {
stream.write(" ");
}
}
stream.write("\n");
}
示例12: onClick
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bStart:
startRecording();
break;
case R.id.bStop:
stopRecording();
break;
case R.id.bExport:
try {
// create and write output file in cache directory
File outputFile = new File(getActivity().getCacheDir(), "recording.csv");
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile));
writer.write(Util.recordingToCSV(mRecording));
writer.close();
// get Uri from FileProvider
Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.martindisch.accelerometer.fileprovider", outputFile);
// create sharing intent
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
// temp permission for receiving app to read this file
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("text/csv");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(Intent.createChooser(shareIntent, "Choose an app"));
} catch (IOException e) {
Toast.makeText(getActivity(), R.string.error_file, Toast.LENGTH_SHORT).show();
}
break;
}
}
示例13: write
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
@Override
protected void write ( final OutputStreamWriter writer ) throws IOException
{
final ScriptSelector content = (ScriptSelector)getContents ().get ( 0 );
if ( content.getScriptEngine () != null && !content.getScriptEngine ().equals ( this.scriptEngine ) )
{
throw new IllegalArgumentException ( String.format ( "Script language must be of type '%s' in order to save it as '%s' file.", this.scriptEngine, this.fileExtension ) );
}
writer.write ( content.getCode () );
}
示例14: sendGvSms
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
/**
* Free software method copied and adapted from Voice.java
* @see http://code.google.com/p/google-voice-java/
*
*/
private String sendGvSms(String smsData) {
Log.i(TAG, "sendGvSms()");
StringBuilder response = new StringBuilder();
try {
// Add the RNR_SE to the message
smsData += "&" + URLEncoder.encode("_rnr_se", UTF8) + "=" + URLEncoder.encode(rnrSEE, UTF8);
Log.i(TAG, "smsData = " + smsData);
URL smsUrl = new URL(GV_SMS_SEND_URL);
HttpURLConnection smsConn = (HttpURLConnection) smsUrl.openConnection();
smsConn.setRequestProperty( "Authorization", "GoogleLogin auth=" + authToken );
smsConn.setRequestProperty("User-agent", USER_AGENT);
setCookies(smsConn);
smsConn.setDoOutput(true);
smsConn.setConnectTimeout(SERVER_TIMEOUT_MS);
Log.i(TAG, "sms request = " + smsConn);
OutputStreamWriter callwr = new OutputStreamWriter(smsConn.getOutputStream());
callwr.write(smsData);
callwr.flush();
processCookies(smsConn);
BufferedReader callrd = new BufferedReader(new InputStreamReader(smsConn.getInputStream()));
String line;
while ((line = callrd.readLine()) != null) {
response.append(line);
response.append("\n"); // HTTP uses \r\n, but Android is built on Linux, so use Unix line endings
}
Log.i(TAG, "sendGvSms: Sent SMS, response = " + response);
callwr.close();
callrd.close();
if (response.length() == 0) {
throw new IOException("No Response Data Received.");
} else {
return response.toString();
}
} catch (IOException e) {
Log.i(TAG, "IO Error on Send " + e.getMessage(), e);
return "IO Error Message not sent";
}
}
示例15: writeTo
import java.io.OutputStreamWriter; //導入方法依賴的package包/類
/**
* Convert the object to a byte stream
*/
public void writeTo(Object obj, String mimeType, OutputStream os)
throws IOException {
if (!(obj instanceof DataSource || obj instanceof Source || obj instanceof String)) {
throw new IOException("Invalid Object type = "+obj.getClass()+
". XmlDataContentHandler can only convert DataSource|Source|String to XML.");
}
ContentType ct = new ContentType(mimeType);
if (!isXml(ct)) {
throw new IOException(
"Invalid content type \"" + mimeType + "\" for XmlDataContentHandler");
}
String charset = ct.getParameter("charset");
if (obj instanceof String) {
String s = (String) obj;
if (charset == null) {
charset = "utf-8";
}
OutputStreamWriter osw = new OutputStreamWriter(os, charset);
osw.write(s, 0, s.length());
osw.flush();
return;
}
Source source = (obj instanceof DataSource)
? (Source)getContent((DataSource)obj) : (Source)obj;
try {
Transformer transformer = XmlUtil.newTransformer();
if (charset != null) {
transformer.setOutputProperty(OutputKeys.ENCODING, charset);
}
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
} catch (Exception ex) {
throw new IOException(
"Unable to run the JAXP transformer in XmlDataContentHandler "
+ ex.getMessage());
}
}