当前位置: 首页>>代码示例>>Java>>正文


Java OutputStream.close方法代码示例

本文整理汇总了Java中java.io.OutputStream.close方法的典型用法代码示例。如果您正苦于以下问题:Java OutputStream.close方法的具体用法?Java OutputStream.close怎么用?Java OutputStream.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.io.OutputStream的用法示例。


在下文中一共展示了OutputStream.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: onComplete

import java.io.OutputStream; //导入方法依赖的package包/类
@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();
    }
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:24,代码来源:AsyncReqProcWithHttpClientCallback.java

示例2: copyAssetFile

import java.io.OutputStream; //导入方法依赖的package包/类
/**
 * 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();
}
 
开发者ID:ngageoint,项目名称:geopackage-android-map,代码行数:27,代码来源:TestUtils.java

示例3: doPost

import java.io.OutputStream; //导入方法依赖的package包/类
@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();
	
}
 
开发者ID:GroupControlDroid,项目名称:GroupControlDroidClient,代码行数:25,代码来源:AddTextServlet.java

示例4: createAccount

import java.io.OutputStream; //导入方法依赖的package包/类
/**
 * 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());
    }
}
 
开发者ID:RightMesh,项目名称:microraiden-java,代码行数:25,代码来源:MicroRaiden.java

示例5: testFailToFlush

import java.io.OutputStream; //导入方法依赖的package包/类
/**
 * 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()));
}
 
开发者ID:l294265421,项目名称:ZooKeeper,代码行数:27,代码来源:AtomicFileOutputStreamTest.java

示例6: handle

import java.io.OutputStream; //导入方法依赖的package包/类
@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();
	}
 
开发者ID:SimplifiedLogic,项目名称:creoson,代码行数:28,代码来源:JshellHttpHandler.java

示例7: post

import java.io.OutputStream; //导入方法依赖的package包/类
/**
 *  鍙戦�丳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();
}
 
开发者ID:bubicn,项目名称:bubichain-sdk-java,代码行数:52,代码来源:HttpKit.java

示例8: saveChartAsJPEG

import java.io.OutputStream; //导入方法依赖的package包/类
/**
 * 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();

}
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:29,代码来源:ChartUtilities.java

示例9: taskFinished

import java.io.OutputStream; //导入方法依赖的package包/类
@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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:34,代码来源:DesignSupport.java

示例10: testWriteLowerMinimumSize

import java.io.OutputStream; //导入方法依赖的package包/类
@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();
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:30,代码来源:B2LargeUploadWriteFeatureTest.java

示例11: testBasePropertiesAlwaysPresent

import java.io.OutputStream; //导入方法依赖的package包/类
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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:34,代码来源:SCFTHandlerTest.java

示例12: testWriteConf

import java.io.OutputStream; //导入方法依赖的package包/类
@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();
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:28,代码来源:TestWriteConfigurationToDFS.java

示例13: extractAsset

import java.io.OutputStream; //导入方法依赖的package包/类
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();
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:8,代码来源:FileManager.java

示例14: c

import java.io.OutputStream; //导入方法依赖的package包/类
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);
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:15,代码来源:WechatHelper.java

示例15: execute

import java.io.OutputStream; //导入方法依赖的package包/类
@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();
	}
}
 
开发者ID:edgexfoundry,项目名称:device-bacnet,代码行数:36,代码来源:ScheduleEventHTTPExecutor.java


注:本文中的java.io.OutputStream.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。