fully understand Java byte arrays and file reads and writes
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException; public class Filehelper {<span style= "White-space:pre" > </span>//the first way to get the contents of a file public byte[] GetContent (stri
Ng FilePath) throws IOException {File File = new file (FilePath);
Long fileSize = File.length ();
if (FileSize > Integer.max_value) {System.out.println ("file Too big ...");
return null;
FileInputStream fi = new FileInputStream (file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numread = 0;
while (Offset < buffer.length && (Numread = fi.read (buffer, offset, buffer.length-offset)) >= 0) {
Offset + + Numread;
//Ensure that all data is read if (offset!= buffer.length) {throw new IOException ("Could not completely read file"
+ File.getname ());
} fi.close ();
return buffer; }//SecondType get file content way public byte[] GetContent2 (String filePath) throws IOException {FileInputStream in=new fileinputstream (f
Ilepath);
Bytearrayoutputstream out=new Bytearrayoutputstream (1024);
System.out.println ("bytes available:" +in.available ());
Byte[] Temp=new byte[1024];
int size=0;
while ((Size=in.read (temp))!=-1) {out.write (temp,0,size);
} in.close ();
Byte[] Bytes=out.tobytearray ();
System.out.println ("bytes size got is:" +bytes.length);
return bytes; ///write byte array to file public void CreateFile (String path, byte[] content) throws IOException {FileOutputStream Fos =
New FileOutputStream (path);
Fos.write (content);
Fos.close ();
}
}
The above a comprehensive understanding of Java byte Array and file reading and writing is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.