java.io.BufferedInputStream#close ( )源码实例Demo

下面列出了java.io.BufferedInputStream#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

public static void main(String[] args) throws Exception {
    File file = new File(System.getProperty("test.src", "."), "ding.dls");
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    try
    {
        InputStream badis = new BadInputStream(bis);
        Soundbank dls = new DLSSoundbankReader().getSoundbank(badis);
        assertTrue(dls.getInstruments().length == 1);
        Patch patch = dls.getInstruments()[0].getPatch();
        assertTrue(patch.getProgram() == 0);
        assertTrue(patch.getBank() == 0);
    }
    finally
    {
        bis.close();
    }
}
 
源代码2 项目: uyuni   文件: CrashHandler.java
/**
 * Download a base64 encoded crash file.
 * @param loggedInUser The current user
 * @param crashFileId Crash File ID
 * @return Return a byte array of the crash file.
 * @throws IOException if there is an exception
 *
 * @xmlrpc.doc Download a crash file.
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param("int", "crashFileId")
 * @xmlrpc.returntype #array_single("byte", "base64 encoded crash file")
 */
public byte[] getCrashFile(User loggedInUser, Integer crashFileId) throws IOException {
    CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(loggedInUser,
            crashFileId.longValue());
    String path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" +
                  crashFile.getCrash().getStoragePath() + "/" +
                  crashFile.getFilename();
    File file = new File(path);

    if (file.length() > freeMemCoeff * Runtime.getRuntime().freeMemory()) {
        throw new CrashFileDownloadException("api.crashfile.download.toolarge");
    }

    byte[] plainFile = new byte[(int) file.length()];
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream br = new BufferedInputStream(fis);
    if (br.read(plainFile) != file.length()) {
        throw new CrashFileDownloadException("api.package.download.ioerror");
    }

    fis.close();
    br.close();

    return Base64.encodeBase64(plainFile);
}
 
public static void main(String[] args) throws Exception {
    File file = new File(System.getProperty("test.src", "."), "ding.sf2");
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    try
    {
        Soundbank sf2 = new SF2SoundbankReader().getSoundbank(bis);
        assertTrue(sf2.getInstruments().length == 1);
        Patch patch = sf2.getInstruments()[0].getPatch();
        assertTrue(patch.getProgram() == 0);
        assertTrue(patch.getBank() == 0);
    }
    finally
    {
        bis.close();
    }
}
 
源代码4 项目: AnimatedFrames   文件: GifDecoder.java
/**
 * Reads GIF image from stream
 *
 * @param is containing GIF file.
 * @return read status code (0 = no errors)
 */
public int read(BufferedInputStream is) {
	init();
	if (is != null) {
		in = is;
		readHeader();
		if (!err()) {
			readContents();
			if (frameCount < 0) {
				status = STATUS_FORMAT_ERROR;
			}
		}
	} else {
		status = STATUS_OPEN_ERROR;
	}
	try {
		is.close();
	} catch (IOException e) {
	}
	return status;
}
 
源代码5 项目: jdk8u-jdk   文件: TestGetSoundbankInputStream2.java
public static void main(String[] args) throws Exception {
    File file = new File(System.getProperty("test.src", "."), "ding.dls");
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    try
    {
        InputStream badis = new BadInputStream(bis);
        Soundbank dls = new DLSSoundbankReader().getSoundbank(badis);
        assertTrue(dls.getInstruments().length == 1);
        Patch patch = dls.getInstruments()[0].getPatch();
        assertTrue(patch.getProgram() == 0);
        assertTrue(patch.getBank() == 0);
    }
    finally
    {
        bis.close();
    }
}
 
源代码6 项目: appinventor-extensions   文件: Web.java
private static String saveResponseContent(HttpURLConnection connection,
    String responseFileName, String responseType) throws IOException {
  File file = createFile(responseFileName, responseType);

  BufferedInputStream in = new BufferedInputStream(getConnectionStream(connection), 0x1000);
  try {
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file), 0x1000);
    try {
      // Copy the contents from the input stream to the output stream.
      while (true) {
        int b = in.read();
        if (b == -1) {
          break;
        }
        out.write(b);
      }
      out.flush();
    } finally {
      out.close();
    }
  } finally {
    in.close();
  }

  return file.getAbsolutePath();
}
 
源代码7 项目: Ticket-Analysis   文件: DirContext.java
public static void copyFile(File sourceFile, File targetFile)
        throws IOException {
    // 新建文件输入流并对它进行缓冲
    FileInputStream input = new FileInputStream(sourceFile);
    BufferedInputStream inBuff = new BufferedInputStream(input);

    // 新建文件输出流并对它进行缓冲
    FileOutputStream output = new FileOutputStream(targetFile);
    BufferedOutputStream outBuff = new BufferedOutputStream(output);

    // 缓冲数组
    byte[] b = new byte[1024 * 5];
    int len;
    while ((len = inBuff.read(b)) != -1) {
        outBuff.write(b, 0, len);
    }
    // 刷新此缓冲的输出流
    outBuff.flush();

    //关闭流
    inBuff.close();
    outBuff.close();
    output.close();
    input.close();
}
 
源代码8 项目: ForgePE   文件: MainActivity.java
public byte[] getFileDataBytes(String filename) {
    if (filename.isEmpty())
        return null;

    try {
        AssetManager assets = getAssets();
        InputStream is = assets.open(filename);
        BufferedInputStream bis = new BufferedInputStream(is);

        int buffer = 1048576;
        ByteArrayOutputStream s = new ByteArrayOutputStream(buffer);

        byte[] tmp = new byte[buffer];

        int count;
        while ((count = bis.read(tmp)) != -1)
            s.write(tmp, 0, count);
        bis.close();

        return s.toByteArray();
    } catch (IOException e) {
        System.err.println("Cannot read from file " + filename);
        return null;
    }
}
 
源代码9 项目: systemsgenetics   文件: DoubleMatrixDataset.java
private void loadRowObjects(String fileName) throws FileNotFoundException, IOException {

        rowObjects = new ArrayList<T>(nrRows);
        File fileRows = new File(fileName + ".rows.ser");
//            File fileRows = new File(fileName + ".rows.gson");

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileRows));
        ObjectInputStream ois = new ObjectInputStream(bis);

//            TextFile tf = new TextFile(fileName + ".rows.gson", false);
//            String line;
//            Type type = new TypeToken<T>() {
//            }.getType(); // workaround for generics
//            Gson gson = new Gson();
//            while ((line = tf.readLine()) != null) {
//                T fromJson = gson.fromJson(line, type);
//                rowObjects.add(fromJson);
//            }
//            tf.close();

        try {
            while (bis.available() > 0) {
                rowObjects.add((T) ois.readObject());
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DoubleMatrixDataset.class.getName()).log(Level.SEVERE, "Error with row objects", ex);
            ex.printStackTrace();
        }
        bis.close();
        ois.close();
        if (rowObjects.size() != nrRows) {
            throw new IOException("The number of row objects in " + fileRows.getName() + " doesn't match the number of rows in " + fileName + ".dat");
        }

    }
 
源代码10 项目: kotlogram   文件: DefaultAESImplementation.java
@Override
public void AES256IGEEncrypt(String sourceFile, String destFile, byte[] iv, byte[] key) throws IOException {

    File src = new File(sourceFile);
    File dest = new File(destFile);

    AESFastEngine engine = new AESFastEngine();
    engine.init(true, new KeyParameter(key));

    byte[] curIvX = substring(iv, 16, 16);
    byte[] curIvY = substring(iv, 0, 16);

    BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(src));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(dest));
    byte[] buffer = new byte[16];
    int count;
    while ((count = inputStream.read(buffer)) > 0) {
        byte[] outData = new byte[16];
        for (int j = 0; j < 16; j++) {
            outData[j] = (byte) (buffer[j] ^ curIvY[j]);
        }
        engine.processBlock(outData, 0, outData, 0);
        for (int j = 0; j < 16; j++) {
            outData[j] = (byte) (outData[j] ^ curIvX[j]);
        }

        curIvX = buffer;
        curIvY = outData;
        buffer = new byte[16];

        outputStream.write(outData);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
}
 
源代码11 项目: aptoide-client-v8   文件: DeepLinkIntentReceiver.java
private void downloadMyAppFile(String myappUri) throws Exception {
  try {
    URL url = new URL(myappUri);
    URLConnection connection;
    if (!myappUri.startsWith("file://")) {
      connection = url.openConnection();
      connection.setReadTimeout(5000);
      connection.setConnectTimeout(5000);
    } else {
      connection = url.openConnection();
    }

    BufferedInputStream getit = new BufferedInputStream(connection.getInputStream(), 1024);

    File file_teste = new File(TMP_MYAPP_FILE);
    if (file_teste.exists()) {
      file_teste.delete();
    }

    FileOutputStream saveit = new FileOutputStream(TMP_MYAPP_FILE);
    BufferedOutputStream bout = new BufferedOutputStream(saveit, 1024);
    byte data[] = new byte[1024];

    int readed = getit.read(data, 0, 1024);
    while (readed != -1) {
      bout.write(data, 0, readed);
      readed = getit.read(data, 0, 1024);
    }

    bout.close();
    getit.close();
    saveit.close();
  } catch (Exception e) {
    CrashReport.getInstance()
        .log(e);
  }
}
 
源代码12 项目: jdk8u-jdk   文件: UBiDiProps.java
public UBiDiProps() throws IOException{
    InputStream is=ICUData.getStream(DATA_FILE_NAME);
    BufferedInputStream b=new BufferedInputStream(is, 4096 /* data buffer size */);
    readData(b);
    b.close();
    is.close();

}
 
源代码13 项目: red5-server-common   文件: FileUtil.java
/**
 * Special method for capture of StdOut.
 * 
 * @return stdOut thread
 */
private final static Thread stdOut(final Process p) {
    final byte[] empty = new byte[128];
    for (int b = 0; b < empty.length; b++) {
        empty[b] = (byte) 0;
    }
    Thread std = new Thread() {
        public void run() {
            StringBuilder sb = new StringBuilder(1024);
            byte[] buf = new byte[128];
            BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
            log.debug("Process output:");
            try {
                while (bis.read(buf) != -1) {
                    sb.append(new String(buf).trim());
                    // clear buffer
                    System.arraycopy(empty, 0, buf, 0, buf.length);
                }
                log.debug(sb.toString());
                bis.close();
            } catch (Exception e) {
                log.error("{}", e);
            }
        }
    };
    std.setDaemon(true);
    std.start();
    return std;
}
 
源代码14 项目: yawl   文件: DownloadWorker.java
@Override
protected Void doInBackground() {
    int bufferSize = 8192;
    byte[] buffer = new byte[bufferSize];
    int progress = 0;
    try {
        URL webFile = _fileNode.getAbsoluteURL();
        makeDir(_fileNode.getDiskFilePath());
        String fileTo = _tmpDir + File.separator + _fileNode.getDiskFilePath();
        BufferedInputStream inStream = new BufferedInputStream(webFile.openStream());
        FileOutputStream fos = new FileOutputStream(fileTo);
        BufferedOutputStream outStream = new BufferedOutputStream(fos);

        // read chunks from the input stream and write them out
        int bytesRead;
        while ((bytesRead = inStream.read(buffer, 0, bufferSize)) > 0) {
            outStream.write(buffer, 0, bytesRead);
            progress += bytesRead;
            setProgress(Math.min((int) (progress * 100 / _totalBytes), 100));
            if (isCancelled()) {
                outStream.close();
                inStream.close();
                new File(fileTo).delete();
                break;
            }
        }

        outStream.close();
        inStream.close();
    }
    catch (Exception e) {
        e.printStackTrace();
        _errorMsg = e.getMessage();
    }

    return null;
}
 
源代码15 项目: RP-DBSCAN   文件: Methods.java
public void findCoreWithSpecificMeta(int readOrder, List<ApproximatedCell> grids) throws IOException, ClassNotFoundException
{
	float[] coords = new float[dim];
	List<Integer> neighborIdList = new ArrayList<Integer>();
	
	List<Integer> key = null;
	List<ApproximatedPoint> innerPts = null;
	int comp = (int)(Math.ceil(Math.sqrt(dim)));
		
	BufferedInputStream bi = new BufferedInputStream(new FileInputStream(new File(SparkFiles.get(metaPaths.get(readOrder)))));	
	GZIPInputStream gis = new GZIPInputStream(bi);
	ObjectInputStream ois = new ObjectInputStream(gis);
	Dictionary meta = (Dictionary)ois.readObject();
	ois.close();
	gis.close();
	bi.close();
		
	meta.buildNeighborSearchTree();
		
	for(ApproximatedCell grid : grids)
	{
		key = grid.cellCoords;
		innerPts = grid.pts;
			
		if( grid.ifFullCore || !meta.isContainCell(key))
			continue;

		//find neighbor cell from i th partition
		for(int j=0; j<dim; j++)
			coords[j] = (float)key.get(j);
					
		neighborIdList.clear();
		meta.neighborTree.getNeighborId(meta.neighborTree.root, coords, neighborIdList, comp);
			
		int state = 0;
		int cnt = 0;
			
		for(int j=0; j<neighborIdList.size(); j++)
		{						
			List<Integer> neighborCoords = meta.getIntGirdCoordsIndex(neighborIdList.get(j));
			Kdtree kdtree = meta.lvp_neighborTrees.get(neighborIdList.get(j));
			NeighborCell neighbor = new NeighborCell(neighborCoords, kdtree);

			for(ApproximatedPoint pt : innerPts)
			{
				if(pt.isCore)	continue;
				cnt = pt.neighborPts;

				//state check
				state = pt.stateWithSphere(neighbor.cellId, dim, sqr_r, meta.level_1_SideLen);
				if(state == 1)
					cnt += neighbor.lv_p_kdtree.count;
				else if(state == 0)
				{
					List<Kdnode> lv_p_neighbor = new ArrayList<Kdnode>();
					neighbor.lv_p_kdtree.getNeighborNode(neighbor.lv_p_kdtree.root, pt.coords, lv_p_neighbor, eps);
					for(Kdnode node: lv_p_neighbor)
					{
						if(Norm.sqr_L2_norm(pt.coords, node.coords) <= sqr_r)
							cnt += node.count;
						if(cnt >= minPts)
							break;
					}
				}
					
				pt.neighborPts = cnt;	
					
				if(cnt >= minPts)
					pt.isCore = true;
			}
		}
	}
	meta = null;
}
 
源代码16 项目: openjdk-8   文件: UnpackerImpl.java
/**
 * Takes a packed-stream InputStream, and writes to a JarOutputStream. Internally
 * the entire buffer must be read, it may be more efficient to read the packed-stream
 * to a file and pass the File object, in the alternate method described below.
 * <p>
 * Closes its input but not its output.  (The output can accumulate more elements.)
 * @param in an InputStream.
 * @param out a JarOutputStream.
 * @exception IOException if an error is encountered.
 */
public synchronized void unpack(InputStream in, JarOutputStream out) throws IOException {
    if (in == null) {
        throw new NullPointerException("null input");
    }
    if (out == null) {
        throw new NullPointerException("null output");
    }
    assert(Utils.currentInstance.get() == null);
    TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE))
                  ? null
                  : TimeZone.getDefault();

    try {
        Utils.currentInstance.set(this);
        if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        final int verbose = props.getInteger(Utils.DEBUG_VERBOSE);
        BufferedInputStream in0 = new BufferedInputStream(in);
        if (Utils.isJarMagic(Utils.readMagic(in0))) {
            if (verbose > 0)
                Utils.log.info("Copying unpacked JAR file...");
            Utils.copyJarFile(new JarInputStream(in0), out);
        } else if (props.getBoolean(Utils.DEBUG_DISABLE_NATIVE)) {
            (new DoUnpack()).run(in0, out);
            in0.close();
            Utils.markJarFile(out);
        } else {
            try {
                (new NativeUnpack(this)).run(in0, out);
            } catch (UnsatisfiedLinkError | NoClassDefFoundError ex) {
                // failover to java implementation
                (new DoUnpack()).run(in0, out);
            }
            in0.close();
            Utils.markJarFile(out);
        }
    } finally {
        _nunp = null;
        Utils.currentInstance.set(null);
        if (tz != null) TimeZone.setDefault(tz);
    }
}
 
源代码17 项目: WeChatEnterprise   文件: MaterialManager.java
/**
 * 获取临时素材
 * 
 * @param access_token
 *            凭证
 * @param mediaId
 *            媒体文件id
 * @param savePath
 *            获取媒体文件成功后,保存的地址
 * @param resp
 *            请求结果回调接口
 */
public static void getTemporaryMaterial(String access_token, String mediaId, String savePath, HttpResponse resp) {

	String filePath = null;
	// 拼接请求地址
	String url = String.format(WXApi.WX_GET_TEMPORARY_MATERIAL, access_token, mediaId);

	try {

		URL getUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) getUrl.openConnection();
		conn.setDoInput(true);
		conn.setRequestMethod(WXApi.GET);

		// 根据内容类型获取扩展名
		String fileExt = WXHttpUtil.getFileEndWitsh(conn.getHeaderField("Content-Type")).trim();

		// 判断Content类型
		if (fileExt.equals("json")) {

			// 获取媒体文件上传的输入流(从微信服务器读数据)
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			StringBuffer buffer = new StringBuffer();
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;

			if (resp != null)
				resp.onOk(JSONObject.fromObject(buffer.toString()));

		} else {

			if (!savePath.endsWith("/")) {
				savePath += "/";
			}

			// 将mediaId作为文件名
			filePath = savePath + mediaId + fileExt;

			System.out.println("filePath = " + filePath);

			File file = new File(filePath);
			if (file.exists())
				file.delete();

			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);

			fos.close();
			bis.close();
			conn.disconnect();
		}

	} catch (Exception e) {

		if (resp != null)
			resp.onError(e.getCause());
	}

}
 
源代码18 项目: jdk8u_jdk   文件: Font2DTest.java
private void loadOptions( String fileName ) {
    try {
        BufferedInputStream bis =
          new BufferedInputStream( new FileInputStream( fileName ));
        int numBytes = bis.available();
        byte byteData[] = new byte[ numBytes ];
        bis.read( byteData, 0, numBytes );
        bis.close();
        if ( numBytes < 2 ||
            (byteData[0] != (byte) 0xFE || byteData[1] != (byte) 0xFF) )
          throw new Exception( "Not a Font2DTest options file" );

        String options = new String( byteData, "UTF-16" );
        StringTokenizer perLine = new StringTokenizer( options, "\n" );
        String title = perLine.nextToken();
        if ( !title.equals( "Font2DTest Option File" ))
          throw new Exception( "Not a Font2DTest options file" );

        /// Parse all options
        boolean displayGridOpt = Boolean.parseBoolean( perLine.nextToken() );
        boolean force16ColsOpt = Boolean.parseBoolean( perLine.nextToken() );
        boolean showFontInfoOpt = Boolean.parseBoolean( perLine.nextToken() );
        String rangeNameOpt = perLine.nextToken();
        int rangeStartOpt = Integer.parseInt( perLine.nextToken() );
        int rangeEndOpt = Integer.parseInt( perLine.nextToken() );
        String fontNameOpt = perLine.nextToken();
        float fontSizeOpt = Float.parseFloat( perLine.nextToken() );
        int fontStyleOpt = Integer.parseInt( perLine.nextToken() );
        int fontTransformOpt = Integer.parseInt( perLine.nextToken() );
        int g2TransformOpt = Integer.parseInt( perLine.nextToken() );
        int textToUseOpt = Integer.parseInt( perLine.nextToken() );
        int drawMethodOpt = Integer.parseInt( perLine.nextToken() );
        int antialiasOpt = Integer.parseInt(perLine.nextToken());
        int fractionalOpt = Integer.parseInt(perLine.nextToken());
        int lcdContrast = Integer.parseInt(perLine.nextToken());
        String userTextOpt[] = { "Font2DTest!" };
        String dialogEntry = "Font2DTest!";
        if (textToUseOpt == fp.USER_TEXT )  {
            int numLines = perLine.countTokens(), lineNumber = 0;
            if ( numLines != 0 ) {
                userTextOpt = new String[ numLines ];
                dialogEntry = "";
                for ( ; perLine.hasMoreElements(); lineNumber++ ) {
                    userTextOpt[ lineNumber ] = perLine.nextToken();
                    dialogEntry += userTextOpt[ lineNumber ] + "\n";
                }
            }
        }

        /// Reset GUIs
        displayGridCBMI.setState( displayGridOpt );
        force16ColsCBMI.setState( force16ColsOpt );
        showFontInfoCBMI.setState( showFontInfoOpt );
        rm.setSelectedRange( rangeNameOpt, rangeStartOpt, rangeEndOpt );
        fontMenu.setSelectedItem( fontNameOpt );
        sizeField.setText( String.valueOf( fontSizeOpt ));
        styleMenu.setSelectedIndex( fontStyleOpt );
        transformMenu.setSelectedIndex( fontTransformOpt );
        transformMenuG2.setSelectedIndex( g2TransformOpt );
        textMenu.setSelectedIndex( textToUseOpt );
        methodsMenu.setSelectedIndex( drawMethodOpt );
        antiAliasMenu.setSelectedIndex( antialiasOpt );
        fracMetricsMenu.setSelectedIndex( fractionalOpt );
        contrastSlider.setValue(lcdContrast);

        userTextArea.setText( dialogEntry );
        updateGUI();

        if ( textToUseOpt == fp.FILE_TEXT ) {
          tFileName = perLine.nextToken();
          readTextFile(tFileName );
        }

        /// Reset option variables and repaint
        fp.loadOptions( displayGridOpt, force16ColsOpt,
                        rangeStartOpt, rangeEndOpt,
                        fontNameOpt, fontSizeOpt,
                        fontStyleOpt, fontTransformOpt, g2TransformOpt,
                        textToUseOpt, drawMethodOpt,
                        antialiasOpt, fractionalOpt,
                        lcdContrast, userTextOpt );
        if ( showFontInfoOpt ) {
            fireUpdateFontInfo();
            fontInfoDialog.show();
        }
        else
          fontInfoDialog.hide();
    }
    catch ( Exception ex ) {
        fireChangeStatus( "ERROR: Failed to Load Options File; See Stack Trace", true );
        ex.printStackTrace();
    }
}
 
源代码19 项目: jeewx-api   文件: WXUpload.java
/**
	 * 
	 * @param accessToken
	 * @param type 有image 类型
	 * @param fileUrl 一定要注意  这个类型为全路径名称哦
	 * @return
	 */
	public static JSONObject upload(String accessToken, String type, String fileUrl) {
		JSONObject jsonObject = null;
		String last_wechat_url = upload_wechat_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
		// 定义数据分割符
		String boundary = "----------sunlight";
		try {
			URL uploadUrl = new URL(last_wechat_url);
			HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
			uploadConn.setDoOutput(true);
			uploadConn.setDoInput(true);
			uploadConn.setRequestMethod("POST");
			// 设置请求头Content-Type
			uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			// 获取媒体文件上传的输出流(往微信服务器写数据)
			OutputStream outputStream = uploadConn.getOutputStream();

			URL mediaUrl = new URL(fileUrl);
			HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
			meidaConn.setDoOutput(true);
			meidaConn.setRequestMethod("GET");

			// 从请求头中获取内容类型
			String contentType = meidaConn.getHeaderField("Content-Type");
			String filename=getFileName(fileUrl,contentType);
			// 请求体开始
			outputStream.write(("--" + boundary + "\r\n").getBytes());
			outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", filename).getBytes());
			outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());

			// 获取媒体文件的输入流(读取文件)
			BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
			byte[] buf = new byte[1024 * 8];
			int size = 0;
			while ((size = bis.read(buf)) != -1) {
				// 将媒体文件写到输出流(往微信服务器写数据)
				outputStream.write(buf, 0, size);
			}
			// 请求体结束
			outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
			outputStream.close();
			bis.close();
			meidaConn.disconnect();

			// 获取媒体文件上传的输入流(从微信服务器读数据)
			InputStream inputStream = uploadConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			StringBuffer buffer = new StringBuffer();
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			uploadConn.disconnect();
			// 使用json解析
//			jsonObject = JSONObject.fromObject(buffer.toString());
			jsonObject = JSONObject.parseObject(buffer.toString());
			System.out.println("jsonobject="+jsonObject);
		} catch (Exception e) {
			System.out.println("上传文件失败!");
			e.printStackTrace();
		}
		return jsonObject;
	}
 
源代码20 项目: dragonwell8_jdk   文件: RuleBasedBreakIterator.java
protected byte[] readFile(final String datafile)
    throws IOException, MissingResourceException {

    BufferedInputStream is;
    try {
        is = AccessController.doPrivileged(
            new PrivilegedExceptionAction<BufferedInputStream>() {
                @Override
                public BufferedInputStream run() throws Exception {
                    return new BufferedInputStream(getClass().getResourceAsStream("/sun/text/resources/" + datafile));
                }
            }
        );
    }
    catch (PrivilegedActionException e) {
        throw new InternalError(e.toString(), e);
    }

    int offset = 0;

    /* First, read magic, version, and header_info. */
    int len = LABEL_LENGTH + 5;
    byte[] buf = new byte[len];
    if (is.read(buf) != len) {
        throw new MissingResourceException("Wrong header length",
                                           datafile, "");
    }

    /* Validate the magic number. */
    for (int i = 0; i < LABEL_LENGTH; i++, offset++) {
        if (buf[offset] != LABEL[offset]) {
            throw new MissingResourceException("Wrong magic number",
                                               datafile, "");
        }
    }

    /* Validate the version number. */
    if (buf[offset] != supportedVersion) {
        throw new MissingResourceException("Unsupported version(" + buf[offset] + ")",
                                           datafile, "");
    }

    /* Read data: totalDataSize + 8(for checksum) */
    len = getInt(buf, ++offset);
    buf = new byte[len];
    if (is.read(buf) != len) {
        throw new MissingResourceException("Wrong data length",
                                           datafile, "");
    }

    is.close();

    return buf;
}