Java Code Examples for java.io.OutputStreamWriter#close()

The following examples show how to use java.io.OutputStreamWriter#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpRequest.java    From hoko-android with Apache License 2.0 6 votes vote down vote up
/**
 * Performs an HttpPost to the specified url, will handle the response with the callback.
 *
 * @param httpCallback The HttpRequestCallback object.
 * @throws IOException Throws an IOException in case of a network problem.
 */
private void performPOST(HttpRequestCallback httpCallback) throws IOException {
    URL url = getUrl();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    applyHttpsHostnameVerifier(connection, url);
    connection.setRequestMethod("POST");
    applyHeaders(connection, true);
    HokoLog.d("POST to " + getUrl() + " with " + getParameters());
    if (getParameters() != null) {
        connection.setDoOutput(true);
        OutputStreamWriter outputStreamWriter =
                new OutputStreamWriter(connection.getOutputStream());
        outputStreamWriter.write(getParameters());
        outputStreamWriter.flush();
        outputStreamWriter.close();
    }

    handleHttpResponse(connection, httpCallback);
}
 
Example 2
Source File: TalkClient.java    From Talk with MIT License 6 votes vote down vote up
/** 
 * 保存聊天记录
 */
private void saveTalkRecord() {
	File dir = new File(talkRecordDir);
	if(! dir.exists()) dir.mkdir();
	if(usrsMsg == null) return;
	for(Map.Entry<String, String> usr: usrsMsg.entrySet()) {
		File file = new File(talkRecordDir + "/" + usr.getKey() + ".txt");
		try {
			FileOutputStream fos = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
			osw.write(usr.getValue());
			osw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
Example 3
Source File: AbstractContentTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Writes the supplied text out to a temporary file, and opens
 *  a content reader onto it. 
 */
protected static ContentReader buildContentReader(String text, Charset encoding)
    throws IOException
{
    File tmpFile = TempFileProvider.createTempFile("AlfrescoTest_", ".txt");
    FileOutputStream out = new FileOutputStream(tmpFile);
    OutputStreamWriter wout = new OutputStreamWriter(out, encoding);
    wout.write(text);
    wout.close();
    out.close();
    
    ContentReader reader = new FileContentReader(tmpFile);
    reader.setEncoding(encoding.displayName());
    reader.setMimetype("text/plain");
    return reader;
}
 
Example 4
Source File: GsonHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	Charset charset = getCharset(outputMessage.getHeaders());
	OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset);
	try {
		if (this.jsonPrefix != null) {
			writer.append(this.jsonPrefix);
		}
		if (type != null) {
			this.gson.toJson(o, type, writer);
		}
		else {
			this.gson.toJson(o, writer);
		}
		writer.close();
	}
	catch (JsonIOException ex) {
		throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
	}
}
 
Example 5
Source File: MarketoBaseRESTClient.java    From components with Apache License 2.0 6 votes vote down vote up
public RequestResult executePostRequest(Class<?> resultClass, JsonObject inputJson) throws MarketoException {
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod(QUERY_METHOD_POST);
        urlConn.setRequestProperty(REQUEST_PROPERTY_CONTENT_TYPE, REQUEST_VALUE_APPLICATION_JSON);
        urlConn.setRequestProperty(REQUEST_PROPERTY_ACCEPT, REQUEST_VALUE_TEXT_JSON);
        urlConn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
        wr.write(inputJson.toString());
        wr.flush();
        wr.close();
        return (RequestResult) new Gson().fromJson(getReaderFromHttpResponse(urlConn), resultClass);
    } catch (IOException e) {
        LOG.error("GET request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}
 
Example 6
Source File: SvmORLearner.java    From jatecs with GNU General Public License v3.0 5 votes vote down vote up
static void generateClassificationData(String outFile, IIndex index,
                                       int docID) throws IOException {
    File dir = new File(outFile).getParentFile();
    if (!dir.exists())
        dir.mkdirs();

    FileOutputStream os = new FileOutputStream(outFile);
    OutputStreamWriter out = new OutputStreamWriter(os);

    StringBuilder b = new StringBuilder();
    b.append(index.getCategoryDB()
            .getCategoryName(
                    index.getClassificationDB()
                            .getDocumentCategories(docID).next()));

    IIntIterator itFeats = index.getContentDB().getDocumentFeatures(docID);
    while (itFeats.hasNext()) {
        int featID = itFeats.next();
        double score = index.getWeightingDB().getDocumentFeatureWeight(
                docID, featID);
        if (score == 0)
            continue;

        b.append(" " + (featID + 1) + ":" + score);
    }

    b.append(Os.newline());

    out.write(b.toString());

    out.close();
}
 
Example 7
Source File: FileResourcesUtil.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean writeToFile(@NonNull String content, @Nullable String secretToEncode) {
    // Get the directory for the user's public pictures directory.
    final File path = new File(Environment.getExternalStorageDirectory(), "DHIS2");

    // Make sure the path directory exists.
    if (!path.exists()) {
        // Make it, if it doesn't exit
        path.mkdirs();
    }

    final File file = new File(path, "dhisDataBuckUp.txt");
    if (file.exists())
        file.delete();

    // Save your stream, don't forget to flush() it before closing it.

    try {
        boolean fileCreated = file.createNewFile();
        try (FileOutputStream fOut = new FileOutputStream(file)) {
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append(content);

            myOutWriter.close();

            fOut.flush();
        }
        return fileCreated;
    } catch (IOException e) {
        Timber.e("File write failed: %s", e.toString());
        return false;
    }
}
 
Example 8
Source File: FreeMarkerView.java    From ask-sdk-frameworks-java with Apache License 2.0 5 votes vote down vote up
@Override
protected String renderInternal(Map<String, Object> model) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
    OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
    try {
        template.process(model, writer);
        writer.close();
        return new String(stream.toByteArray(), StandardCharsets.UTF_8);
    } finally {
        writer.close();
    }
}
 
Example 9
Source File: Logcat2.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public void run() {
		 try {
			 InputStreamReader isr = new InputStreamReader(is,"UTF-8");
			 BufferedReader br = new BufferedReader(isr);
			 
			 osw = new OutputStreamWriter(new FileOutputStream(logcat));
			 bw = new BufferedWriter(osw);
			 
			 String line = null;
			 while (this.stop == false && (line = br.readLine()) != null) {
				 bw.write(line + "\r\n");
//				 if (type.equals("Error"))
//					 error.append(line);
//				 else
//					 info.append(line);
			 }
		 } catch (IOException ioe) {
			 ioe.printStackTrace();
		 }finally {
			 try {
				 if(bw != null)
					 bw.close();
	             if(osw != null)
	            	 osw.close();
			 } catch (IOException e) {
	              e.printStackTrace();
	        }  
		 }
	 }
 
Example 10
Source File: SvmPerfLearner.java    From jatecs with GNU General Public License v3.0 5 votes vote down vote up
static void generateClassificationData(String outFile, IIndex index,
                                       int docID, short catID) throws IOException {
    File dir = new File(outFile).getParentFile();
    if (!dir.exists())
        dir.mkdirs();

    FileOutputStream os = new FileOutputStream(outFile);
    OutputStreamWriter out = new OutputStreamWriter(os);

    StringBuilder b = new StringBuilder();
    b.append("0");

    IIntIterator itFeats = index.getDocumentFeatures(docID, catID);
    while (itFeats.hasNext()) {
        int featID = itFeats.next();
        double score = index.getDocumentFeatureWeight(docID, featID, catID);
        if (score == 0)
            continue;

        b.append(" " + (featID + 1) + ":" + score);
    }

    b.append(" #" + Os.newline());

    out.write(b.toString());

    out.close();
    os.close();
}
 
Example 11
Source File: InterfaceB_EnvironmentBasedServer.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // store a copy of the request params for later
        Map<String, String> paramsMap = new HashMap<>();
        Enumeration paramNms = request.getParameterNames();
        while (paramNms.hasMoreElements()) {
            String name = (String) paramNms.nextElement();
            paramsMap.put(name, request.getParameter(name));
        }

        // only a request for parameter info needs a non-default response
        String action = request.getParameter("action");
        String result = "OK";
        if ("ParameterInfoRequest".equals(action)) {
            YParameter[] params = _controller.describeRequiredParams();
            StringBuilder output = new StringBuilder();
            for (YParameter param : params) {
                if (param != null) output.append(param.toXML());
            }
            result = StringUtil.wrap(output.toString(), "response");
        }

        // complete the request/response thread early by sending the default response
        OutputStreamWriter outputWriter = ServletUtils.prepareResponse(response);
        outputWriter.write(result);
        outputWriter.flush();
        outputWriter.close();

        // for all event actions, send the notification to services
       _executor.execute(new EventHandler(paramsMap));
    }
 
Example 12
Source File: File.java    From cjs_ssms with GNU General Public License v2.0 5 votes vote down vote up
public static void write(String path, String content){
	try
       {                     
           OutputStreamWriter out = new OutputStreamWriter(
           		new FileOutputStream(path),"UTF-8");
           //out.write("\n"+content);
           out.write(content);
           out.flush();
           out.close();
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }
}
 
Example 13
Source File: UnicodeTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void generateSource(String thisClass, String otherClass) throws Exception {
    File file = new File(UnicodeTestSrc, thisClass + JAVA_FILE_EXT);
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    out.write("public class " + thisClass + " {\n");
    out.write("    public static void main(String[] args) {\n");
    out.write("        if (!" + otherClass + "." + otherClass.toLowerCase() + "().equals(\"" + otherClass + "\")) {\n");
    out.write("            throw new RuntimeException();\n");
    out.write("        }\n");
    out.write("    }\n");
    out.write("    public static String " + thisClass.toLowerCase() + "() {\n");
    out.write("        return \"" + thisClass + "\";\n");
    out.write("    }\n");
    out.write("}\n");
    out.close();
}
 
Example 14
Source File: IoTest.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
 * 字节流
 * 创建一个文件并读取记录 防止乱码
 * @throws IOException
 */
private static void test4() throws IOException {
	String path="E:/test/hello.txt";
	String path2="E:/test/你好.txt";
	String str="你好!";
	//从文件读取数据
	InputStream input = new FileInputStream(path);
	InputStreamReader reader = new InputStreamReader(input, "UTF-8");
    StringBuffer sb=new StringBuffer();
	while(reader.ready()){
		sb.append((char)reader.read());
	}
	
	input.close();
	reader.close();
	
	//创建一个文件并向文件中写数据
	OutputStream output = new FileOutputStream(path2);
	OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
	writer.write(sb+str);
	
	writer.close();
	output.close();
	
	//从文件读取数据
	InputStream input2 = new FileInputStream(path2);
	InputStreamReader reader2 = new InputStreamReader(input2, "UTF-8");
    StringBuffer sb2=new StringBuffer();
	while(reader2.ready()){
		sb2.append((char)reader2.read());
	}
	System.out.println("输出:"+sb2);
	input2.close();
	reader2.close();
}
 
Example 15
Source File: DataBackup.java    From scada with MIT License 4 votes vote down vote up
/**
 * �������ݿ�
 * @param databaseFilePath ���ݵ�·��
 */
public static void backup(String databaseFilePath) {
       try {
           Runtime rt = Runtime.getRuntime();

           // ���� mysql �� cmd:
           //mysqldump -uroot -proot --set-charset=utf8 scada
           Process child = rt
                   .exec("mysqldump -u"+new ReadProperties().getProperties("db.properties", "jdbc.user")
                   		+" -p"+new ReadProperties().getProperties("db.properties", "jdbc.password")+" --set-charset=utf8 scada");// ���õ�������Ϊutf8�����������utf8

           // �ѽ���ִ���еĿ���̨�����Ϣд��.sql�ļ����������˱����ļ���ע��������Կ���̨��Ϣ���ж�������ᵼ�½��̶����޷�����
           InputStream in = child.getInputStream();// ����̨�������Ϣ��Ϊ������

           InputStreamReader xx = new InputStreamReader(in, "utf8");// �������������Ϊutf8�����������utf8����������ж����������

           String inStr;
           StringBuffer sb = new StringBuffer("");
           String outStr;
           // ��Ͽ���̨�����Ϣ�ַ���
           BufferedReader br = new BufferedReader(xx);
           while ((inStr = br.readLine()) != null) {
               sb.append(inStr + "\r\n");
           }
           outStr = sb.toString();
           // Ҫ�����������õ�sqlĿ���ļ���
           FileOutputStream fout = new FileOutputStream(
           		databaseFilePath+"scada.sql");
           OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
           writer.write(outStr);
           // ע����������û��巽ʽд���ļ��Ļ����ᵼ���������룬��flush()��������Ա���
           writer.flush();

           // �����ǹر����������
           in.close();
           xx.close();
           br.close();
           writer.close();
           fout.close();

           System.out.println("/* Output OK! */");

       } catch (Exception e) {
           e.printStackTrace();
       }

   }
 
Example 16
Source File: GenerateSplitAbiRes.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@TaskAction
protected void doFullTaskAction() throws IOException, InterruptedException, ProcessException {

    for (String split : getSplits()) {
        String resPackageFileName = getOutputFileForSplit(split).getAbsolutePath();

        File tmpDirectory = new File(getOutputDirectory(), getOutputBaseName());
        tmpDirectory.mkdirs();

        File tmpFile = new File(tmpDirectory, "AndroidManifest.xml");

        String versionNameToUse = getVersionName();
        if (versionNameToUse == null) {
            versionNameToUse = String.valueOf(getVersionCode());
        }

        OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(tmpFile), "UTF-8");
        try {
            fileWriter.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                    + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"
                    + "      package=\"" + getApplicationId() + "\"\n"
                    + "      android:versionCode=\"" + getVersionCode() + "\"\n"
                    + "      android:versionName=\"" + versionNameToUse + "\"\n"
                    + "      split=\"lib_" + getOutputBaseName() + "\">\n"
                    + "       <uses-sdk android:minSdkVersion=\"21\"/>\n" + "</manifest> ");
            fileWriter.flush();
        } finally {
            fileWriter.close();
        }

        AaptPackageProcessBuilder aaptPackageCommandBuilder =
                new AaptPackageProcessBuilder(tmpFile, getAaptOptions())
                    .setDebuggable(isDebuggable())
                    .setResPackageOutput(resPackageFileName);

        getBuilder().processResources(
                aaptPackageCommandBuilder,
                false /* enforceUniquePackageName */,
                new LoggedProcessOutputHandler(getILogger()));
    }
}
 
Example 17
Source File: SSL_Client_json_simple.java    From firehose_examples with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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();
    }
}
 
Example 18
Source File: OldCamActivity.java    From goprohero with MIT License 4 votes vote down vote up
public void startGPSLog(View view){
    gps = new GPStracker(OldCamActivity.this);
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy--HH-mm-ss");
    //get current date time with Date()
    Date date = new Date();
    String thedate = dateFormat.format(date);
    DateFormat dateFormatTwo = new SimpleDateFormat("dd-MM-yyyy");
    //get current date time with Date()
    Date dateTwo = new Date();
    String theotherdate = dateFormatTwo.format(dateTwo);
    String thisfiledate = dateFormatTwo.format(dateTwo);
    // check if GPS enabled
    if(gps.canGetLocation()){

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        // \n is for new line
        Toast.makeText(getApplicationContext(), "GPS Tracking started", Toast.LENGTH_LONG).show();
        try {
            File myFile = new File("/sdcard/GoProGPSTrack" + theotherdate + ".txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =
                    new OutputStreamWriter(fOut);
            myOutWriter.append("<gpx>");
            myOutWriter.append("<trk>");
            myOutWriter.append("<name>GoPro Track</name>");
            myOutWriter.append("<trkseg>");
            myOutWriter.append("<latitude>" + latitude + "</latitude>");
            myOutWriter.append("<longitude>" + longitude + "</longitude>");
            myOutWriter.append("<time>" + date + "</time>");
            myOutWriter.append("</trkseg>");
            myOutWriter.close();
            fOut.close();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }else{
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
    }

}
 
Example 19
Source File: CsvInputFormatTest.java    From flink with Apache License 2.0 4 votes vote down vote up
private void testRemovingTrailingCR(String lineBreakerInFile, String lineBreakerSetup) {
	File tempFile = null;

	String fileContent = CsvInputFormatTest.FIRST_PART + lineBreakerInFile + CsvInputFormatTest.SECOND_PART + lineBreakerInFile;

	try {
		// create input file
		tempFile = File.createTempFile("CsvInputFormatTest", "tmp");
		tempFile.deleteOnExit();
		tempFile.setWritable(true);

		OutputStreamWriter wrt = new OutputStreamWriter(new FileOutputStream(tempFile));
		wrt.write(fileContent);
		wrt.close();

		final TupleTypeInfo<Tuple1<String>> typeInfo = TupleTypeInfo.getBasicTupleTypeInfo(String.class);
		final CsvInputFormat<Tuple1<String>> inputFormat = new TupleCsvInputFormat<Tuple1<String>>(new Path(tempFile.toURI().toString()), typeInfo);

		Configuration parameters = new Configuration();
		inputFormat.configure(parameters);

		inputFormat.setDelimiter(lineBreakerSetup);

		FileInputSplit[] splits = inputFormat.createInputSplits(1);

		inputFormat.open(splits[0]);

		Tuple1<String> result = inputFormat.nextRecord(new Tuple1<String>());

		assertNotNull("Expecting to not return null", result);

		assertEquals(FIRST_PART, result.f0);

		result = inputFormat.nextRecord(result);

		assertNotNull("Expecting to not return null", result);
		assertEquals(SECOND_PART, result.f0);

	}
	catch (Throwable t) {
		System.err.println("test failed with exception: " + t.getMessage());
		t.printStackTrace(System.err);
		fail("Test erroneous");
	}
}
 
Example 20
Source File: IoUtil.java    From Vert.X-generator with MIT License 3 votes vote down vote up
/**
 * 将字符串存储为文件
 * 
 * @param dir
 *            目录
 * @param fileName
 *            文件名称
 * @param materi
 *            字符串内容
 * @param codeFormat
 *            字符编码方式
 * @throws Exception
 */
public static void StrToFile(Path dir, String fileName, String materi, String codeFormat) throws Exception {
	if (!isExists(dir)) {
		createDir(dir);
	}
	Path path = Paths.get(dir.toString(), fileName);
	OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE);
	OutputStreamWriter writer = new OutputStreamWriter(out, codeFormat);
	writer.write(materi);
	writer.flush();
	out.close();
	writer.close();
}