Java Code Examples for java.io.OutputStream.close()

The following are Jave code examples for showing how to use close() of the java.io.OutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: uavstack   File: AsyncReqProcWithHttpClientCallback.java   View Source Code Vote up 7 votes
@Override
public void onComplete(AsyncEvent arg0) throws IOException {

    // 返回信息

    OutputStream os = ac.getResponse().getOutputStream();
    InputStream is = response.getEntity().getContent();

    // 调用微信平台的Callback
    HttpClientCallbackResult result = new HttpClientCallbackResult(is, os);
    result.setRetCode(getStatusCode());
    try {
        callback.completed(result);
    }
    catch (RuntimeException e) {
        // ignore
    }
    finally {
        os.flush();
        os.close();
        is.close();
    }
}
 
Example 2
Project: geopackage-android-map   File: TestUtils.java   View Source Code Vote up 6 votes
/**
 * Copy the asset file to the provided file path
 *
 * @param testContext
 * @param assetPath
 * @param filePath
 * @throws IOException
 */
private static void copyAssetFile(Context testContext, String assetPath,
                                  String filePath) throws IOException {

    InputStream assetFile = getAssetFileStream(testContext, assetPath);

    OutputStream newFile = new FileOutputStream(filePath);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = assetFile.read(buffer)) > 0) {
        newFile.write(buffer, 0, length);
    }

    // Close the streams
    newFile.flush();
    newFile.close();
    assetFile.close();
}
 
Example 3
Project: GroupControlDroidClient   File: AddTextServlet.java   View Source Code Vote up 6 votes
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException, IOException {
	String group_id_str = req.getParameter("group_id");
	String text=req.getParameter("text");
	Long user_id=AuthConfig.getUser_id();
	String token=AuthConfig.getToken();
	
	OutputStream os=resp.getOutputStream();
	OperationBean respBean=new OperationBean();
	if (group_id_str!=null&&text!=null&&user_id>0&&token!=null) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("token", token);
		data.put("user_id", user_id.toString());
		data.put("group_id", group_id_str);
		data.put("text", text);
		
		String returnAnswer = HttpRequest.post(authUrl).form(data).body();
		os.write(returnAnswer.getBytes("UTF-8"));
	}
	os.flush();
	os.close();
	
}
 
Example 4
Project: microraiden-java   File: MicroRaiden.java   View Source Code Vote up 6 votes
/**
 * Create a new Ethereum account to be used for testing microraiden
 * channels. Stores the account in the same folder where the
 * program is run. Note - there is no encryption on this private key
 * so it should be used for anything real!!
 * @param accountFile - the name of the output file for the account
 */
public void createAccount(String accountFile) {
    ECKey keyPair = new ECKey();
    String address = new String(Hex.encodeHex(keyPair.getAddress()));
    System.out.println("Generated new account: 0x" + address);
    byte[] priv = keyPair.getPrivKeyBytes();
    
    try {
        OutputStream os = new FileOutputStream(accountFile + ".pkey");
        JSONObject obj=new JSONObject();
        obj.put("privkey", new String(Hex.encodeHex(priv)));
        obj.put("address", address);
        os.write(obj.toJSONString().getBytes());
        os.close();
    } catch (IOException e) {
        System.out.println("Couldn't write to file: " + accountFile + " " + e.toString());
    }
}
 
Example 5
Project: ZooKeeper   File: AtomicFileOutputStreamTest.java   View Source Code Vote up 6 votes
/**
 * Test case where the flush() fails at close time - make sure that we clean
 * up after ourselves and don't touch any existing file at the destination
 */
@Test
public void testFailToFlush() throws IOException {
    // Create a file at destination
    FileOutputStream fos = new FileOutputStream(dstFile);
    fos.write(TEST_STRING_2.getBytes());
    fos.close();

    OutputStream failingStream = createFailingStream();
    failingStream.write(TEST_STRING.getBytes());
    try {
        failingStream.close();
        fail("Close didn't throw exception");
    } catch (IOException ioe) {
        // expected
    }

    // Should not have touched original file
    assertEquals(TEST_STRING_2, ClientBase.readFile(dstFile));

    assertEquals("Temporary file should have been cleaned up",
            dstFile.getName(), ClientBase.join(",", testDir.list()));
}
 
Example 6
Project: creoson   File: JshellHttpHandler.java   View Source Code Vote up 6 votes
@Override
	public void handle(HttpExchange t) throws IOException {

		// retrieve the request json data
		InputStream is = t.getRequestBody();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len;
		while ((len = is.read(buffer))>0) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		String data = new String(bos.toByteArray(), Charset.forName("UTF-8"));
		logit("Request: \n    " + data);

		// pass the data to the handler and receive a response
		String response = handler.handleRequest(data);
		logit("    " + response);
		
		// format and return the response to the user
		t.sendResponseHeaders(200, response.getBytes(Charset.forName("UTF-8")).length);
//		t.getResponseHeaders().set("Content-Type", "application/json");
		t.getResponseHeaders().set("Content-Type", "application/json, charset=UTF-8");
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes(Charset.forName("UTF-8")));
		os.close();
	}
 
Example 7
Project: bubichain-sdk-java   File: HttpKit.java   View Source Code Vote up 5 votes
/**
 *  鍙戦�丳ost璇锋眰
 * @param url
 * @param params
 * @return
 * @throws IOException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	StringBuffer bufferRes = null;
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄  
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL urlGet = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
    // 杩炴帴瓒呮椂
    http.setConnectTimeout(50000);
    // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
    http.setReadTimeout(50000);
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    http.setSSLSocketFactory(ssf);
    http.setHostnameVerifier(new Verifier());
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();

    OutputStream out = http.getOutputStream();
    out.write(params.getBytes("UTF-8"));
    out.flush();
    out.close();

    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null){
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        // 鍏抽棴杩炴帴
        http.disconnect();
    }
    return bufferRes.toString();
}
 
Example 8
Project: parabuild-ci   File: ChartUtilities.java   View Source Code Vote up 5 votes
/**
 * Saves a chart to a file in JPEG format.  This method allows you to pass in a
 * {@link ChartRenderingInfo} object, to collect information about the chart
 * dimensions/entities.  You will need this info if you want to create an HTML image map.
 *
 * @param file  the file name (<code>null</code> not permitted).
 * @param quality  the quality setting.
 * @param chart  the chart (<code>null</code> not permitted).
 * @param width  the image width.
 * @param height  the image height.
 * @param info  the chart rendering info (<code>null</code> permitted).
 *
 * @throws IOException if there are any I/O errors.
 */
public static void saveChartAsJPEG(File file,
                                   float quality,
                                   JFreeChart chart,
                                   int width,
                                   int height,
                                   ChartRenderingInfo info) throws IOException {

    if (file == null) throw new IllegalArgumentException("Null 'file' argument.");
    if (chart == null) throw new IllegalArgumentException("Null 'chart' argument.");
    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    writeChartAsJPEG(out, quality, chart, width, height, info);
    out.close();

}
 
Example 9
Project: incubator-netbeans   File: DesignSupport.java   View Source Code Vote up 5 votes
@Override
public void taskFinished(Task task) {
    FileObject modeDir = userDir.get().getFileObject("config/Windows2Local/Modes");
    OutputStream os;
    if (modeDir != null) {
        StringBuilder sb = new StringBuilder();
        try {
            
            FileSystem layer = findLayer(project);
            if (layer == null) {
                throw new IOException("Cannot find layer in " + project); // NOI18N
            }
            for (FileObject m : modeDir.getChildren()) {
                if (m.isData() && "wsmode".equals(m.getExt())) { 
                    final String name = "Windows2/Modes/" + m.getNameExt(); // NOI18N
                    FileObject mode = FileUtil.createData(layer.getRoot(), name); // NOI18N
                    os = mode.getOutputStream();
                    os.write(DesignSupport.readMode(m).getBytes("UTF-8")); // NOI18N
                    os.close();
                    sb.append(name).append("\n");
                }
            }
            NotifyDescriptor nd = new NotifyDescriptor.Message(
                NbBundle.getMessage(DesignSupport.class, "MSG_ModesGenerated", new Object[] {sb}), 
                NotifyDescriptor.INFORMATION_MESSAGE
            );
            DialogDisplayer.getDefault().notifyLater(nd);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    EventQueue.invokeLater(this);
}
 
Example 10
Project: cyberduck   File: B2LargeUploadWriteFeatureTest.java   View Source Code Vote up 5 votes
@Test
public void testWriteLowerMinimumSize() throws Exception {
    final B2Session session = new B2Session(
            new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
                    new Credentials(
                            System.getProperties().getProperty("b2.user"), System.getProperties().getProperty("b2.key")
                    )));
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final B2LargeUploadWriteFeature feature = new B2LargeUploadWriteFeature(session);
    final Path container = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final OutputStream out = feature.write(file, status, new DisabledConnectionCallback());
    final byte[] content = new RandomStringGenerator.Builder().build().generate(2 * 1024 * 1024).getBytes("UTF-8");
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    assertEquals(content.length, IOUtils.copy(in, out));
    in.close();
    out.close();
    assertTrue(new B2FindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new B2ReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new B2DeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 11
Project: incubator-netbeans   File: SCFTHandlerTest.java   View Source Code Vote up 5 votes
public void testBasePropertiesAlwaysPresent() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    String txt = "print('<html><h1>'); print(name); print('</h1>');" +
        "print('<h2>'); print(date); print('</h2>');" +
        "print('<h3>'); print(time); print('</h3>');" +
        "print('<h4>'); print(user); print('</h4>');" +
        "print('<h4>'); print(dateTime.getTime()); print('</h4>');" +
        "print('</html>');";
    os.write(txt.getBytes());
    os.close();
    fo.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "js");
    
    
    DataObject obj = DataObject.find(fo);
    
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    Map<String,String> parameters = Collections.singletonMap("title", "Nazdar");
    DataObject n = obj.createFromTemplate(folder, "complex", parameters);
    
    assertEquals("Created in right place", folder, n.getFolder());
    assertEquals("Created with right name", "complex.txt", n.getName());
    
    String res = readFile(n.getPrimaryFile());
    
    if (res.indexOf("date") >= 0) fail(res);
    if (res.indexOf("time") >= 0) fail(res);
    if (res.indexOf("user") >= 0) fail(res);
    if (res.indexOf("name") >= 0) fail(res);
    if (res.indexOf("dateTime") >= 0) fail(res);
}
 
Example 12
Project: hadoop   File: TestWriteConfigurationToDFS.java   View Source Code Vote up 5 votes
@Test(timeout=60000)
public void testWriteConf() throws Exception {
  Configuration conf = new HdfsConfiguration();
  conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 4096);
  System.out.println("Setting conf in: " + System.identityHashCode(conf));
  MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
  FileSystem fs = null;
  OutputStream os = null;
  try {
    fs = cluster.getFileSystem();
    Path filePath = new Path("/testWriteConf.xml");
    os = fs.create(filePath);
    StringBuilder longString = new StringBuilder();
    for (int i = 0; i < 100000; i++) {
      longString.append("hello");
    } // 500KB
    conf.set("foobar", longString.toString());
    conf.writeXml(os);
    os.close();
    os = null;
    fs.close();
    fs = null;
  } finally {
    IOUtils.cleanup(null, os, fs);
    cluster.shutdown();
  }
}
 
Example 13
Project: javaide   File: FileManager.java   View Source Code Vote up 5 votes
public static void extractAsset(Context zContext, String zAssetFile, File zOuput) throws IOException {
    InputStream in = zContext.getAssets().open(zAssetFile);
    OutputStream os = new FileOutputStream(zOuput);
    copyStream(in, os);
    in.close();
    os.close();
}
 
Example 14
Project: boohee_v5.6   File: WechatHelper.java   View Source Code Vote up 5 votes
private void c(Context context, String str, String str2, String str3, Bitmap bitmap, int i, k kVar) {
    IMediaObject wXFileObject = new WXFileObject();
    wXFileObject.filePath = str3;
    WXMediaMessage wXMediaMessage = new WXMediaMessage();
    wXMediaMessage.title = str;
    wXMediaMessage.description = str2;
    wXMediaMessage.mediaObject = wXFileObject;
    OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 100, byteArrayOutputStream);
    byteArrayOutputStream.flush();
    byteArrayOutputStream.close();
    wXMediaMessage.thumbData = a(context, byteArrayOutputStream.toByteArray());
    a(wXMediaMessage, "filedata", i, kVar);
}
 
Example 15
Project: device-bacnet   File: ScheduleEventHTTPExecutor.java   View Source Code Vote up 5 votes
@Async
public void execute(final ScheduleEvent event) {
	int returnCode;
	String body = event.getParameters();
	if(body == null) body = "";
	final String url = getURL(event.getAddressable());

	String method = event.getAddressable().getMethod().toString();

	try {
		if (url == null) {
			logger.info("no address for schedule event " + event.getName());
		} else {
			URL obj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod(method);
			con.setDoOutput(true);
			con.setConnectTimeout(timeout);
			con.setRequestProperty("Content-Type", "application/json");
			con.setRequestProperty("Content-Length", "" + body.length());
			OutputStream os = null;
			try {
				os = con.getOutputStream();
				os.write(body.getBytes());
				returnCode = con.getResponseCode();
			} finally {
				os.close();
			}
			logger.debug("executed event " + event.getId() + " '" + event.getName() + "' response code " + returnCode + " url '" + url + "' body '" + body + "'");
		} 
	} catch (Exception e) {
		logger.error("exception executing event " + event.getId() + " '" + event.getName() + "' url '" + url + "' body '" + body + "' exception " + e.getMessage());
		e.printStackTrace();
	}
}
 
Example 16
Project: boohee_v5.6   File: a.java   View Source Code Vote up 5 votes
private String a(Bitmap bitmap, a aVar) {
    try {
        File createTempFile = File.createTempFile("bm_tmp", ".png");
        OutputStream fileOutputStream = new FileOutputStream(createTempFile);
        bitmap.compress(CompressFormat.PNG, 100, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        return a(createTempFile.getAbsolutePath(), aVar);
    } catch (Throwable th) {
        Ln.e(th);
        return null;
    }
}
 
Example 17
Project: ViraPipe   File: Interleave.java   View Source Code Vote up 5 votes
private static void decompress(FileSystem fs, String in, String outpath) throws IOException {

    Configuration conf = new Configuration();
    CompressionCodecFactory factory = new CompressionCodecFactory(conf);
    CompressionCodec codec = factory.getCodec(new Path(in));
    //Decompressing zip file.
    InputStream is = codec.createInputStream(fs.open(new Path(in)));
    OutputStream out = fs.create(new Path(outpath));
    //Write decompressed out
    IOUtils.copyBytes(is, out, conf);
    is.close();
    out.close();
  }
 
Example 18
Project: rure   File: CaptchaUtil.java   View Source Code Vote up 4 votes
public void write(OutputStream sos) throws IOException {
	ImageIO.write(buffImg, "png", sos);
	sos.close();
}
 
Example 19
Project: boohee_v5.6   File: AsynLoadImg.java   View Source Code Vote up 4 votes
public boolean saveFile(Bitmap bitmap, String str) {
    IOException e;
    OutputStream outputStream;
    Throwable th;
    String str2 = c;
    BufferedOutputStream bufferedOutputStream = null;
    try {
        File file = new File(str2);
        if (!file.exists()) {
            file.mkdir();
        }
        str2 = str2 + str;
        f.a("AsynLoadImg", "saveFile:" + str);
        OutputStream bufferedOutputStream2 = new BufferedOutputStream(new FileOutputStream
                (new File(str2)));
        try {
            bitmap.compress(CompressFormat.JPEG, 80, bufferedOutputStream2);
            bufferedOutputStream2.flush();
            if (bufferedOutputStream2 != null) {
                try {
                    bufferedOutputStream2.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
            return true;
        } catch (IOException e3) {
            e2 = e3;
            outputStream = bufferedOutputStream2;
            try {
                e2.printStackTrace();
                f.a("AsynLoadImg", "saveFile bmp fail---");
                if (bufferedOutputStream != null) {
                    return false;
                }
                try {
                    bufferedOutputStream.close();
                    return false;
                } catch (IOException e4) {
                    e4.printStackTrace();
                    return false;
                }
            } catch (Throwable th2) {
                th = th2;
                if (bufferedOutputStream != null) {
                    try {
                        bufferedOutputStream.close();
                    } catch (IOException e42) {
                        e42.printStackTrace();
                    }
                }
                throw th;
            }
        } catch (Throwable th3) {
            th = th3;
            outputStream = bufferedOutputStream2;
            if (bufferedOutputStream != null) {
                bufferedOutputStream.close();
            }
            throw th;
        }
    } catch (IOException e5) {
        e2 = e5;
        e2.printStackTrace();
        f.a("AsynLoadImg", "saveFile bmp fail---");
        if (bufferedOutputStream != null) {
            return false;
        }
        bufferedOutputStream.close();
        return false;
    }
}
 
Example 20
Project: incubator-netbeans   File: DynamicSFSFallbackTest.java   View Source Code Vote up 4 votes
private static void write(FileObject fo, String txt) throws IOException {
    OutputStream os = fo.getOutputStream();
    os.write(txt.getBytes());
    os.close();
}