下面列出了java.io.BufferedOutputStream#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 保存文件
* @param file 文件
* @param data 待存储数据
* @return {@code true} success, {@code false} fail
*/
public static boolean saveFile(final File file, final byte[] data) {
if (file != null && data != null) {
try {
// 防止文件夹没创建
createFolder(getDirName(file));
// 写入文件
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(data);
bos.close();
fos.close();
return true;
} catch (Exception e) {
JCLogUtils.eTag(TAG, e, "saveFile");
}
}
return false;
}
public static boolean inputStreamToFile(InputStream inputStream, String filename, String tmpSuffix) throws IOException {
BufferedInputStream bis = new BufferedInputStream(inputStream);
// 存储加临时后缀,避免重名
File file = new File(filename + tmpSuffix);
File parent = file.getParentFile();
if (parent != null && (!parent.exists())) {
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, CACHED_SIZE);
int count;
byte data[] = new byte[CACHED_SIZE];
while ((count = bis.read(data, 0, CACHED_SIZE)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
bos.close();
bis.close();
return renameFile(file, filename);
}
/**
* Handle image processing in Firebase and Cloud Vision.
*/
private void onPictureTaken(final byte[] imageBytes) {
Log.d(TAG, "PhotoCamera onPictureTaken");
if (imageBytes != null) {
String imageStr = Base64.encodeToString(imageBytes, Base64.NO_WRAP | Base64.URL_SAFE);
Log.d(TAG, "imageBase64:"+imageStr);
final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
if (bitmap != null) {
File file=new File(HttpServer.wwwRoot + "pic.jpg");//将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
picVersion++;
}
}
}
/**
* 写图片文件到SD卡
*
* @throws IOException
*/
public static void saveImageToSD(Context ctx, String filePath,
Bitmap bitmap, int quality) throws IOException {
if (bitmap != null) {
File file = new File(filePath.substring(0,
filePath.lastIndexOf(File.separator)));
if (!file.exists()) {
file.mkdirs();
}
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(filePath));
bitmap.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
if (ctx != null) {
scanPhoto(ctx, filePath);
}
}
}
/**
* 保存文件
* @param bm
* @throws IOException
*/
public static String saveFile(Bitmap bm) throws IOException {
File dirFile = new File(ALBUM_PATH);
if(!dirFile.exists()){
dirFile.mkdir();
}
File myCaptureFile = new File(ALBUM_PATH + SystemClock.currentThreadTimeMillis() +".png");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
return myCaptureFile.getAbsolutePath();
}
/**
* Gzip compress a string
* @param string the string to compress
* @return the compressed data
*/
public static byte[] gzipCompress(String string) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
GZIPOutputStream gz = new GZIPOutputStream(stream);
BufferedOutputStream bufos = new BufferedOutputStream(gz, 5000000);
bufos.write(string.getBytes());
bufos.flush();
bufos.close();
return stream.toByteArray();
}
catch (IOException e) {
return null;
}
}
@SuppressWarnings("rawtypes")
public static void unZipWithPath(String zipFullPath, String zipCategory) {
try {
String fileName = zipFullPath; //��Ҫ��ѹ���ļ�zip��ַ
//String filePath = zipCategory; //��ѹ����ַ
ZipFile zipFile = new ZipFile(fileName);
Enumeration emu = zipFile.entries();
while(emu.hasMoreElements()){
ZipEntry entry = (ZipEntry)emu.nextElement();
if (entry.isDirectory()){
//new File(filePath + entry.getName()).mkdirs();
new File(entry.getName()).mkdirs();
continue;
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(zipFile.getInputStream(entry));
File file = new File(entry.getName());
File parent = file.getParentFile();
if(parent != null && (!parent.exists())){
parent.mkdirs();
}
if(!file.getPath().contains(".lyg")) {
file.mkdirs();
}else {
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream,BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bufferedInputStream.read(data, 0, BUFFER)) != -1){
bufferedOutputStream.write(data, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
bufferedInputStream.close();
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void unzip(String zipFile, String outputFile) throws IOException {
try {
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
try {
ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) {
if (ze.isDirectory()) {
File unzipFile = new File(outputFile);
if(!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
}
else {
FileOutputStream fout = new FileOutputStream(outputFile, false);
BufferedOutputStream bufout = new BufferedOutputStream(fout);
try {
byte[] buffer = new byte[2048];
int read;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
}
finally {
zin.closeEntry();
bufout.close();
fout.close();
}
}
}
}
finally {
zin.close();
}
}
catch (Exception e) {
Log.e(TAG, "Unzip exception", e);
}
}
/**
* Extracts a zip entry (file entry)
* @param zipIn
* @param filePath
* @throws IOException
*/
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {
// throws IllegalArgumentException if not supported
AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);
// first write the file without worrying about length fields
FileOutputStream fos = new FileOutputStream( out ); // throws IOException
BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
int bytesWritten = writeAuFile(stream, auFileFormat, bos );
bos.close();
// now, if length fields were not specified, calculate them,
// open as a random access file, write the appropriate fields,
// close again....
if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
// $$kk: 10.22.99: jan: please either implement this or throw an exception!
// $$fb: 2001-07-13: done. Fixes Bug 4479981
RandomAccessFile raf=new RandomAccessFile(out, "rw");
if (raf.length()<=0x7FFFFFFFl) {
// skip AU magic and data offset field
raf.skipBytes(8);
raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
// that's all
}
raf.close();
}
return bytesWritten;
}
public static void main(String[] args) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("bos.txt"));
// 写数据
bos.write("hello".getBytes());
// 释放资源
bos.close();
}
/**
* Helper method to decrypt file
* @param inputStream stream associated with encrypted file
* @param outputStream stream associated with new output decrypted file
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws UnrecoverableKeyException
* @throws KeyStoreException
* @throws NoSuchProviderException
* @throws InvalidAlgorithmParameterException
* @throws IOException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private static void aesDecrypt(BufferedInputStream inputStream, BufferedOutputStream outputStream)
throws NoSuchPaddingException, NoSuchAlgorithmException, CertificateException,
UnrecoverableKeyException, KeyStoreException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException, InvalidKeyException,
BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(ALGO_AES);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), gcmParameterSpec);
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
int count;
try {
while ((count = cipherInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, count);
ServiceWatcherUtil.POSITION+=count;
}
} finally {
outputStream.flush();
cipherInputStream.close();
outputStream.close();
}
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {
// throws IllegalArgumentException if not supported
AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);
// first write the file without worrying about length fields
FileOutputStream fos = new FileOutputStream( out ); // throws IOException
BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
int bytesWritten = writeAuFile(stream, auFileFormat, bos );
bos.close();
// now, if length fields were not specified, calculate them,
// open as a random access file, write the appropriate fields,
// close again....
if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
// $$kk: 10.22.99: jan: please either implement this or throw an exception!
// $$fb: 2001-07-13: done. Fixes Bug 4479981
RandomAccessFile raf=new RandomAccessFile(out, "rw");
if (raf.length()<=0x7FFFFFFFl) {
// skip AU magic and data offset field
raf.skipBytes(8);
raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
// that's all
}
raf.close();
}
return bytesWritten;
}
public static State saveFileByInputStream(InputStream is, String path,
long maxSize) {
State state = null;
File tmpFile = getTmpFile();
byte[] dataBuf = new byte[ 2048 ];
BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
int count = 0;
while ((count = bis.read(dataBuf)) != -1) {
bos.write(dataBuf, 0, count);
}
bos.flush();
bos.close();
if (tmpFile.length() > maxSize) {
tmpFile.delete();
return new BaseState(false, AppInfo.MAX_SIZE);
}
state = saveTmpFile(tmpFile, path);
if (!state.isSuccess()) {
tmpFile.delete();
}
return state;
} catch (IOException e) {
}
return new BaseState(false, AppInfo.IO_ERROR);
}
private void logPatient(Patient modifiedPatient, String prefix) {
File dir = new File("/Library/Application Support/iCure/Patients");
if (dir.exists() && dir.isDirectory()) {
XStream xs = new XStream();
File file = new File(dir, prefix + System.currentTimeMillis() + ".xml");
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
xs.toXML(modifiedPatient, out);
out.close();
} catch (java.io.IOException ignored) {
//
}
}
}
public static void saveToFile(InputStream in, File file) throws IOException {
File outputFile = file;
outputFile.deleteOnExit();
outputFile.getParentFile().mkdirs();
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
byte[] buffer = new byte[2048];
int length = in.read(buffer);
while (length != -1) {
outputStream.write(buffer, 0, length);
length = in.read(buffer);
}
outputStream.flush();
outputStream.close();
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {
// throws IllegalArgumentException if not supported
AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);
// first write the file without worrying about length fields
FileOutputStream fos = new FileOutputStream( out ); // throws IOException
BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
int bytesWritten = writeAuFile(stream, auFileFormat, bos );
bos.close();
// now, if length fields were not specified, calculate them,
// open as a random access file, write the appropriate fields,
// close again....
if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
// $$kk: 10.22.99: jan: please either implement this or throw an exception!
// $$fb: 2001-07-13: done. Fixes Bug 4479981
RandomAccessFile raf=new RandomAccessFile(out, "rw");
if (raf.length()<=0x7FFFFFFFl) {
// skip AU magic and data offset field
raf.skipBytes(8);
raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
// that's all
}
raf.close();
}
return bytesWritten;
}
/**
* @source http://stackoverflow.com/a/27050680
*/
public static void unzip(InputStream zipFile, File targetDirectory) throws Exception {
ZipInputStream in = new ZipInputStream(new BufferedInputStream(zipFile));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = in.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs()) {
throw new Exception("Failed to ensure directory: " + dir.getAbsolutePath());
}
if (ze.isDirectory()) {
continue;
}
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
while ((count = in.read(buffer)) != -1)
out.write(buffer, 0, count);
} finally {
out.close();
}
long time = ze.getTime();
if (time > 0) {
file.setLastModified(time);
}
}
} finally {
in.close();
}
}
/**
* 复制文件或目录
*/
public static boolean copy(File src, File tar) {
try {
LogUtils.verbose(String.format("copy %s to %s", src.getAbsolutePath(), tar.getAbsolutePath()));
if (src.isFile()) {
InputStream is = new FileInputStream(src);
OutputStream op = new FileOutputStream(tar);
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(op);
byte[] bt = new byte[1024 * 8];
while (true) {
int len = bis.read(bt);
if (len == -1) {
break;
} else {
bos.write(bt, 0, len);
}
}
bis.close();
bos.close();
} else if (src.isDirectory()) {
File[] files = src.listFiles();
//noinspection ResultOfMethodCallIgnored
tar.mkdirs();
for (File file : files) {
copy(file.getAbsoluteFile(), new File(tar.getAbsoluteFile(), file.getName()));
}
}
return true;
} catch (Exception e) {
LogUtils.error(e);
return false;
}
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {
// throws IllegalArgumentException if not supported
AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream);
// first write the file without worrying about length fields
FileOutputStream fos = new FileOutputStream( out ); // throws IOException
BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
int bytesWritten = writeAiffFile(stream, aiffFileFormat, bos );
bos.close();
// now, if length fields were not specified, calculate them,
// open as a random access file, write the appropriate fields,
// close again....
if( aiffFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
// $$kk: 10.22.99: jan: please either implement this or throw an exception!
// $$fb: 2001-07-13: done. Fixes Bug 4479981
int ssndBlockSize = (aiffFileFormat.getFormat().getChannels() * aiffFileFormat.getFormat().getSampleSizeInBits());
int aiffLength=bytesWritten;
int ssndChunkSize=aiffLength-aiffFileFormat.getHeaderSize()+16;
long dataSize=ssndChunkSize-16;
int numFrames=(int) (dataSize*8/ssndBlockSize);
RandomAccessFile raf=new RandomAccessFile(out, "rw");
// skip FORM magic
raf.skipBytes(4);
raf.writeInt(aiffLength-8);
// skip aiff2 magic, fver chunk, comm magic, comm size, channel count,
raf.skipBytes(4+aiffFileFormat.getFverChunkSize()+4+4+2);
// write frame count
raf.writeInt(numFrames);
// skip sample size, samplerate, SSND magic
raf.skipBytes(2+10+4);
raf.writeInt(ssndChunkSize-8);
// that's all
raf.close();
}
return bytesWritten;
}