File content as byte array ?

I have the following code :
File file = new File("path/to/file");
And I want to get the content of "file" as a byte array, something like :
byte[] byteArray = file.getContentAsByteArray();
How do I achieve this ?
Cheers !

The following is also possible.
//import java.io.*;import java.nio.channels.*;import
java.nio.ByteBuffer;
java.io.File file = new File("input.txt");
FileInputStream stream = new FileInputStream(file);
java.nio.channels.FileChannel
channel=stream.getChannel();
java.nio.ByteBuffer buffer =
ByteBuffer.allocate((int)file.length());// if length
is larger than Integer.MAX_VALUE iteration must be
used
channel.read(buffer);
channel.close();
stream.close();
byte[] bytes = buffer.array();
// for(int j=0;j<bytes.length;j++)
System.out.println(Integer.toHexString(bytes[j]));
This will, of course, only work in 1.4, because of the java.nio packages.

Similar Messages

  • How to Read a File into a Byte Array??

    I want to make an array of data objects that works as a byffer to write from a file to another file
    do you have any sygestions?

    The way I would do it (if I dont misunderstand your question) is to use FileInputStream to pass in the streaming data source.
    then read the file source to a list object. For example, LikedList.
    then tell the LikedList to transcribe itself to an array of any type, in this case, byte.

  • How to convert  Wav file  in to byte array an vise vers into RMS???????????

    hi Constantinos Loizou
    i m having same problem which u were facing in last month.
    my problem i have to save .WAV file into RMS and then retreive it from RMS.
    my Code is
    Read From RMS
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    if(rsUser.getNumRecords() > 0)
    try {
    byte[] byusrinfo = rsUser.getRecord(1);
    InputStream in = new ByteArrayInputStream(byusrinfo,0,byusrinfo.length);
    p = Manager.createPlayer(in,"audio/x-wav");
    p.start();
    return true;
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    Write in RMS
    try {
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    int idata = is.available();
    byte[] exdata = new byte[idata];
    is.read(exdata);
    if(rsUser.getNumRecords() > 0) {
    rsUser.setRecord(1,exdata,0,exdata.length);
    else {
    rsUser.addRecord(exdata,0,exdata.length);
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace ();
    now i have the file successfully when i retrieve it from RMS and p.reliaze() give me exception
    javax.microedition.media.MediaException: Failed to realize Player: Malformed wave media: expected 'RIFF'
    have u able to solve it. if yes then pls give me solution. or give other solution if this soution is not good
    regardz
    Hassan Mushtaq

    Well, I'm not going to give you your code on a silver platter. You'll need to put some effort in it yourself.
    So look at that available() method yourself an see if you can improve on that. Look at the api docs, there is loads of information there, and often it will give you pointers on why things are not working.

  • Reading in any file and converting to a byte array

    Okay what I am trying to do is to write a program that will read in any file and convert it into a int array so that I can then manipulate the values of the int array and then re-write the file. Once I get the file into an int array I want to try and compress the data with my own algorithm as well as try to write my own encryption algorithm.
    What I have been looking for is code samples that essentially read in the file as a byte array and then I have been trying to convert that byte array into an int array which I could then manipulate. So does anyone have any sample code that essentially takes a file and converts it into an int array and then converts it back into a byte array and write the file. I have found code that is close but I guess I am just too new to this. Any help would be appreciated.

    You can read a whole file into a byte array like this:File f = new File("somefile");
    int size = (int) f.length();
    byte[] contents = new byte[size];
    DataInputStream in = new DataInputStream(
                              new BufferedInputStream(new FileInputStream(f)));
    in.readFully(contents);
    in.close();Note that you need to add in the proper exception handling code. You could also use RandomAccessFile instead of the DataInputStream.
    Writing a byte array to a file is easier; just construct the FileOutputStream, call write on it with the byte array, and close the stream.

  • Loading big files (more than 30MBs)  as byte arrays

    Hello everybody,
    I have an application in which I need to load files as byte arrays, but when I load a file with a size of 30MBs (aprox) or more I get this exception:
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    The code I'm using to load the files is this:
                   byte[] bb = null;
                   Security.addProvider(new BouncyCastleProvider());
                   try{
                        FileInputStream fis =
                        new FileInputStream(file);
                        bb = new byte[fis.available()];
                        fis.read(bb);
                        fis.close();
                   }catch(IOException e){
                        e.printStackTrace();
         any ideas on this issue?'
    thanks,
    johnny

    You really think you need to load the whole shebang
    in one chunk of memory? And even if you get 30MB to
    fit in, what if your file is 10 times that big - what
    then? You need to redesign it so that it scales well.The reason is that I have to digitally sign the file, and the libraries I'm using (BouncyCastle) receive the file as a byte array, so I need to load the file as that to pass it to the libraries :-(
    What do you think?

  • Problem with byte array arguments in webservice method call

    I am using JWSDP 1.5 to generate client stubs for a webservice hosted on a Windows 2000 platform.
    One of the methods of the webservice contains a byte array argument. When our application calls this method passing the contents of a TIFF file as the byte array, the method is failing. I have discovered that tthe reason for the failure is that the byte array in the SOAP message has been truncated and is missing its terminating tag.
    Is this a known problem in JWSDP 1.5? Is there a fix for it? Does JWSDP 1.6 resolve this problem?
    Any assistance will be much appreciated.
    Regards,
    Leo

    I'd like to add the the webservice being invoked by the generated client stubs is rpc/encoded.

  • Issue with reading byte array

    I have a binary file to be read.I want to read the whole file into a byte array. But while doing so the values which are greater than 128 are read as negative values as we have Signedbyte in java(-127 to 128).
    So I tried reading the bytes into the int array as shown in the below code.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
         content= in.readUnsignedByte();
         i++;
    The above function 'readUnsignedByte();' reads byte and stores it into an int array.....But since the file contains around 34000 bytes ....the loop runs 340000 times .....which is a performance hazard.
    After googling for hours ....I could still not find any alternative ....
    I want to read byte and want to store in int array but instead of loop, I want to read the file at once.
    Or is there any way to implement Unsigned Byte in java so that I can read the entire file in byte array without corrupting the values which are greater than 128..
    I have to deliver the code asap .....Please help me out with an alternative solution for this...
    Thanks in advance....

    Thanks for replying ......
    Actually, I need to take the bytes into an array(int or byte array) with decimal values and further process these decimal values.......
    but while reading the file into a byte array the decimal values get corrupted(in case when I read a number greater than 128) but in this case I am able to read the whole file at once(without using any loop) as done by the following code
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         byte b[] = null;
         in.readFully(b);
    and while reading the file in int array as done in the below code is inefficient as the number of times the loop runs is more than 34000..... please suggest me some alternative.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);     
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
                   content= in.readUnsignedByte();
                   i++;

  • File attachments as byte[] objects

    Hello!
    I'm currenly developing a EJB component to send e-mail with attachments.
    I succeeded uploading files to JSP from HTML form and extracting byte[] raw data from all "input type=file" fields.
    After data extraction, I'm currently creating a new instance of a Data class and filling all its fields with file name, file content type and file content (as byte[]).
    My EJB sends e-mail properly when e-mail does not include any attachment, but not when it does.
    This is how typically a file is attached to a MimeMessage:
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileAttachment);
    messageBodyPart.setDataHandler( new DataHandler(source));
    messageBodyPart.setFileName(filenameString);
    The problem resides in fileName. I don't have got any file written to disk, I've got file in memory as byte[] and I don't know hot to create that DataHandler instace using a byte array.
    Plase, could you give me any idea?
    Thanks in advance.
    Best regards.

    Hi all.
    I've suceeded sending attachments as byte[] using this code:
    mpAttachments = new MimeBodyPart();
    //Here is the solution
    DataSource ds = new ByteArrayDataSource(attachment.getBytes(), attachment.getContentType());
    //This ByteArrayDataSource class can be found on demo directory of JavaMail
    DataHandler dh = new DataHandler(ds);
    mpAttachments.setDataHandler(dh);
    mp.addBodyPart(mpAttachments);
    msg.setContent(mp);
    Transport.send(msg);..
    Thanks for spending your time reading this.

  • Is there a memory limitation to byte arrays?

    Everyone,
    I have a huge(16MB) CMYK source file and I am trying to convert it to a sRGB /JPEG file and then compress it.
    When I try to read that file into a byte array it chokes and throws an OutOfMemoryException. Is there a way around this?
    thanks,
    Barat.

    The data looks something like this:
    CCCCC...MMMMM...YYYYY...KKKKK...
    CCCCC...MMMMM...YYYYY...KKKKK...
    where each letter represents one byte.
    For example, the first cyan byte has cyan information
    for 8 pixels -- each bit represents cyan or no cyan, etc.
    The point is to get this data in a viewable form on screen.
    Have tried increasing the heap to 256
    Of course the problem is in a large array that holds the output information, which is ~130M
    The original file size is 16M but this was expanded to eight times the size for the PixelInterleavedSampleModel
    where one data element (a byte in this case) represents one sample of a pixel
    There must be a better way - any suggestions?

  • Maximum size of a byte array?

    Hi,
    I'm trying to read in a file into a byte array as following:
    byte[]inputformat = new byte[1280];
    FileInputStream in= new FileInputStream(file);
    BufferedInputStream buffer= new BufferedInputStream(in);
    int len = buffer.read(inputformat);
    The problem appears when I try to access the 1024th array-element (inputformat[1024]) afterwards. Is there a limitation in the byte-arrays, or prehaps in the buffer.read-method?
    All comments are welcomed!
    Cheers,
    Slafs

    I executed the following code:
    import java.io.*;
    public class BufferTest {
        public static void main(String[] args) {
            try {
                byte[] inputFormat = new byte[1280];
                File inFile = new File(args[0]);
                FileInputStream in = new FileInputStream(inFile);
                BufferedInputStream bis = new BufferedInputStream(in);
                int len = bis.read(inputFormat);
                System.out.println("Read " + len + " bytes");
            catch (IOException e) {
                System.out.println("Error: " + e.toString());
    }To produce the following output:
    $ java BufferTest snapshot1.png
    Read 1280 bytesSo, I am not sure where your problem lies, but I don't think it's in the code you posted.
    Good luck
    Lee

  • Play flv byte array in Air Application

    I'm trying to load and play an FLV from a ByteArray in Air application . I have created small dummy application in  which l am readiong flv from file system .After reading flv file i have byte array so can you please help me out in thi how to p-lay flv from byte array.
    I have searched the web for awnsers and didn't find anything .
    Any help, ideas or something?

    Hi Giuseppe,
    what I do is:
    1. create a file using Captivate
    2. i place a .flv video in this file
    3. save the file as .swf
    4. then i go to dreamweaver and put the swf on a html page.
    Now:
    when viewed in a browser, everything runs fine.
    when i pack this page into an air application (in dreamweaver) the video does not appear,
    instead I get this "Connection Error"
    I do not know a console or log file.
    However, I learned that there is a .xml file located in the same AIR folder that you publish in.
    In this .xml file there is a setting :transparency. in order to playt a .flv file this must not be be "transparent"!
    (i read this somewhere in the net)
    hope that helps
    I will talk to a professional programmer, if I have any news, i will let you know
    Claus

  • How can I load a pdf-file into a byte[]?

    Hello,
    I would like to load a PDF-File into a byte-Array. How can I do this? The standard Streams shouldn't work because this can't be converted into characters. Can it? So, what does work?
    Any idea?
    Bye,
    Wolfang

    Why would someone not do:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = new FileInputStream("foo.pdf");
    byte[] buf = new byte[4096];
    for(int len=-1;(len=is.read(buf))!=-1;)
            baos.write(buf,0,len);
    is.close();
    baos.flush();
    baos.close();
    buf = baos.toByteArray();  // Here are you bytes!You don't need to know the exact size, let ByteArrayOutputStream do it for you. Streams are generally for bytes, Readers/Writers generally for characters. Why exactly did you say: ``The standard Streams shouldn't work because this can't be converted into characters?''

  • How do I read directly from file into byte array

    I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
    try
                //Read File Contents into a Buffered Image
                /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
                 * (at least partially) a problem with non-standard colour models, which is why we set the
                 * destination colour model. The side effect should be standard colour model in subsequent reading.
                BufferedImage bi = null;
                ImageReader ir = null;
                ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
                final Iterator i = ImageIO.getImageReaders(stream);
                if (i.hasNext())
                    ir = (ImageReader) i.next();
                    ir.setInput(stream);
                    ImageReadParam param = ir.getDefaultReadParam();
                    ImageTypeSpecifier typeToUse = null;
                    for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                        ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                        if (type.getColorModel().getColorSpace().isCS_sRGB())
                            typeToUse = type;
                    if (typeToUse != null)
                        param.setDestinationType(typeToUse);
                    bi = ir.read(0, param);
                    //ir.dispose(); seem to reference this in write
                    //stream.close();
                //Write Buffered Image to Byte ArrayOutput Stream
                if (bi != null)
                    //Convert to byte array
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    //Try and find corresponding writer for reader but if not possible
                    //we use JPG (which is always installed) instead.
                    final ImageWriter iw = ImageIO.getImageWriter(ir);
                    if (iw != null)
                        if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Unable to Write Image");
                    else
                        if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                    //Add to image list
                    final byte[] imageData = output.toByteArray();
                    Images.addImage(imageData);
                  

    If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

  • How to create a jar having the contents of the jar in a byte array?

    Hi,
    I have a server and client application. My server returns the contents of the jar in the form of byte array to the client on a particluar method call. Now at the client end, i want to reconstruct the jar to be used. How do I do this?
    The server uses the JarInputStream to read the contents of the jar to be returned. I have tried using the JarOutputStream, but looks like this works fine if we have spearate class files to be added to the jar. Now that I have the contents of the jar itself, how do i recreate the jar?
    Can anyone please help me with this?
    Thanks
    Rajani

    Have you ever gotten the raw byte copy to work? If so, how?
    I download a jar via InputStream and save into a jar file via fileoutputstream. It always gets corrupted in the process. The new Jar file has the exact same number of bytes, but doesn't get past the Manifest on a -tvf. In fact, Winzip can open it fine, but can't extract. So close...yet so far.
    Here is a snapshot of my code:
    BufferedInputStream data1=new BufferedInputStream(con.getInputStream());
    DataInputStream data=new DataInputStream(data1);
    StringBuffer buf=new StringBuffer();
    try{
    while((theChar=data.read()) != -1)
    { buf.append((char)theChar); }
    } catch (Exception z){ logger.info("UpdateThread.read Done Reading jar file");}
    data.close();
    File newFile = new File("C:/MyJar.jar");
    FileOutputStream outstream2 = new FileOutputStream(newFile);
    DataOutputStream outstream1 = new DataOutputStream(outstream2);
    BufferedOutputStream outstream = new BufferedOutputStream(outstream1);
    byte [] bytes = buf.toString().getBytes();
    logger.info("Bytes of new Jar file = " + bytes.length);
    int i;
    for(i=0;i<bytes.length;i++){
    outstream.write(bytes);
    outstream1.close();
    outstream.close();
    Any ideas where I'm going wrong?

  • How to load and display a byte array (jpeg) image file dynamically in Flex?

    My web service client (servlet) received a binary jpeg data from an Image Server. The Flex application invokes the
    servlet via HttpService and receives the binary jpeg data as byte array.  How could it be displayed dynamically
    without writing the byte array to a jpeg file?  Please help (some sample code is very much appreciated).

    JPEGEncoder is only useful for converting BitmapData to ByteArray, not the other way around.
    By the way JPEGEncoder and PNGEncoder are part of the Flex SDK now, so no need to use AS3Lib (alltough it's a good library to have around).
    To display/use a ByteArray as image, use a Loader instance with the loadBytes method.
        Loader.loadBytes(bytes:ByteArray, context:LoaderContext = null);
    Listen for the complete event on the Loader.contentLoaderInfo and get the BitmapData in the event handler.
    private function loadJpeg():void {
        var loader:Loader = new Loader();
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
        //jpgBA is the ByteArray loaded from webservice
        loader.loadBytes(jpgBA);
    private function loaderCompleteHandler(evt:Event):void {
        var t:LoaderInfo = evt.currentTarget as LoaderInfo;
        // display the jpeg in an Image component
        img.source = t.content;
    <mx:Image id="img" scaleContent="false" />

Maybe you are looking for

  • How do I get my documents to open on 'pages'?

    I started writing a college essay today and after doing the introduction the document wont open and it wont tell me why it wont open. My other document still opens fine but if this is going to be a re-occurring problem then I don't want to use this a

  • Photoshop CS5 crashing repeatedly - Logs inside

    If anyone can shed some light on what these logs say, would be greatly appreciated! Crash #1 Process:         Adobe Photoshop CS5 [329] Path:            /Applications/Adobe Photoshop CS5/Adobe Photoshop CS5.app/Contents/MacOS/Adobe Photoshop CS5 Iden

  • Regarding Payment Terms date in MIR0 Transaction

    Hi, This is regarding payment terms date in MIR0 Transaction. Actual Scenario : Pay on the 25th of the next month following the delivery, or if the 25th of the next month following the delivery has been exceeded,pay 10 days from the invoice date. Hel

  • User Rules in Data Mapping in SQL Developer Migration Workbench

    Hi I was trying to add a User Mapping Rule in the Data Mapping, because the options provided where not entirely what I wanted. Adding a new Rule for instance for SQL Server UniqueIdentifier works fine, but when I try to apply the changes it says that

  • Passing parameter to the external process like notepad, calc etrc.

    Dear Experts, Can anyone help me, to find out how can we pass the value parameter, during calling external process like Notepad, Calculator etc. I want to fetch other data related to the parameter from the other ERP. Eg. If I pass 'Hi ' as a paramete