Java files and byte array conversions

Source: Internet
Author: User

/**
* Gets the byte array of the specified file
*/
Private byte[] GetBytes (String filePath) {
byte[] buffer = NULL;
try {
File File = new file (FilePath);
FileInputStream fis = new FileInputStream (file);
Bytearrayoutputstream BOS = new Bytearrayoutputstream (1000);
Byte[] B = new byte[1000];
int n;
while ((n = fis.read (b))! =-1) {
Bos.write (b, 0, N);
}
Fis.close ();
Bos.close ();
Buffer = Bos.tobytearray ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
return buffer;
}

/**
* Based on byte array, generate file
*/
public static void GetFile (byte[] bfile, String filepath,string fileName) {
Bufferedoutputstream BOS = NULL;
FileOutputStream fos = null;
File file = null;
try {
File dir = new file (FilePath);
if (!dir.exists () &&dir.isdirectory ()) {//Determine if the file directory exists
Dir.mkdirs ();
}
File = new file (filepath+ "\ \" +filename);
FOS = new FileOutputStream (file);
BOS = new Bufferedoutputstream (FOS);
Bos.write (bfile);
} catch (Exception e) {
E.printstacktrace ();
} finally {
if (BOS! = NULL) {
try {
Bos.close ();
} catch (IOException E1) {
E1.printstacktrace ();
}
}
if (fos! = null) {
try {
Fos.close ();
} catch (IOException E1) {
E1.printstacktrace ();
}
}
}
}

Java files and byte array conversions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.