Turn byte array into file

hi,
I got a byte array from a file and want to turn it into a file, so i can access it thru the operating system.
byte[] lop = rs.getBytes("data");
can anyone give any help, or a good tutorial to do this.

Check out the API docs for the FileOutputStream class and pay special attention to its
write(byte[]) method.
kind regards,
Jos

Similar Messages

  • How to change the image into byte and byte array into image

    now i am developing one project. i want change the image into byte array and then byte array into image.

    FileInputStream is = new FileInputStream(file);
    byte[] result = IOUtils.toByteArray(is);
    with apache common IO lib

  • Problems turning bytes back into a des key

    hi there-
    i'm writing a client/server application the uses encryption to send files back and forth. i have been able to get my program to receive certificates from the client and server. i have generated a des key using:
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    java.security.Key secretkey = kg.generateKey();
    and I want to send that to the server, encrypted with the public key. i'm trying to do it like this:
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init ( Cipher.ENCRYPT_MODE, key); //key is the public key
    theBytes [] = secretkey.getEncoded(); //send secretkey
    bytesEncrypted [] = cipher.doFinal(theBytes);
    outToServer.writeInt(bytesEncrypted.length);
    outToServer.write(bytesEncrypted);
    the problem is, once i transmit the des key and decrypt it with the private key, i dont know how to turn it back into a des key from the bytes. can someone help me out bigtime and let me know how i can go about doing this?
    thanks a bunch!

    In followup to my previous reply, here is the sample code.
    import java.security.spec.KeySpec;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    public class SecretKeyTest {
         public static void main(String[] args) throws Exception {
              System.out.println(System.getProperty("java.version"));
              KeyGenerator kg = KeyGenerator.getInstance("DES", "SunJCE");
              SecretKey sk1 = kg.generateKey();
              System.out.println(sk1);
              byte [] sk1Bytes = sk1.getEncoded();
              SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
              KeySpec spec = new DESKeySpec(sk1Bytes);
              SecretKey sk2 = skf.generateSecret(spec);
              System.out.println(sk1.equals(sk2) ? "Equal" : "Not Equal");
    }

  • Displaying byte array PDF file in Portal

    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

    Mark,
    Note that the portal sets the content type (e.g, text/html) and encoding
    as the portal page starts rendering. In your case, the
    setContentType() would be useless since the servlet container won't let
    you change it. You can either use a popup browser window for the pdf as
    Kunal suggested, or use an iframe if you want to render the pdf inside
    the portlet window.
    Subbu
    Mark Gilleece wrote:
    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

  • Save byte[] array to file

    Hi,
    I've read a .jpg picture off the hard disk and stored in a byte[] array. I've altered some of the bytes and want to save the file back to .jpg. Is there a method available in java which allows me to do this?
    Thanks and regards,
    Krt_Malta

    FileOutputStream#write(byte[] array).

  • Converting a byte array into int

    Here's my problem, I've read my data from a server into a byte array.
    the array is 12 elements in length representing three int variables.
    int flag;
    int query_a;
    int query_b;
    here's what i receive:
    0 0 0 0 34 0 0 -2 21 0 0 0
    how do i convert these into the int values i need.
    i know the first four are for flag = 0, but how does it convert?
    0000 = 0 for each byte
    00000000 00000000 00000000 00000000 = 0 for each bit?
    or is there a method to convert from a byte to int?

    Look at the ByteBuffer class (part of 1.4.1) - before that, you would have had to manually build your integers using left shift and & operator (not that big of a deal, really).
    Be sure you know the "Endian"-ness of the platform you are reading data from though, otherwise, your ints will not be what you expect!
    - K

  • Bytes array into a wav file

    hi every1, any1 can help plz, how to write bytes from an audio file (which is stored in an array) back into a wave file thanx

    Hi,
    it is something like this:
    byte[] myByteArray;          //your bytearray
    AudioFormat myAudioFormat;     //neccessary to interpret the bytes in the right manner
    long mySampleFrameLength;     //how long your audiodata is
    AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(myByteArray), myAudioFormat, mySampleFrameLength);
    AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("myWaveFile.wav"));

  • Java Array into File Output

    Hello,
    I have a working program that normally, I hand-wire the information into the file and it is stored in an array and I work with it till the end of the program. This is where the problem is coming from.
    Now the document will be in an external file, and the informations needed for the program should be read from the external file;
    At the beginning of the program, the input file will be loaded into the program and the file will be saved at the end of the program. Giving room for editing / adding to the file during program run and at the end save all the information back into same external file.
    Please how am I to go about this? I really need help in here....
    Thanks for your help in advance.
    Regards

    Please don't post the same question in multiple forums. I'm locking this thread as the question seems more appropriate to "New to Java".

  • How to convert bytes[] into File object

    hi
    how to convert byte array into File object
    pls.. help me
    Regards
    srinu

    rrrr007 wrote:
    Hi,
    How to convert bytes[] into multipage File object?? ]There's no such thing as a "multipage File object." You ought to re-read this thread closely, and read the [API docs for File|http://java.sun.com/javase/6/docs/api/java/io/File.html] to clear up your confusion about what a File object is.
    I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream. Then you need a pdf API, like iText or fop. You can't just concatenate pdf files, word docs, excel sheets, etc., like you can text files. Google for java pdf api.

  • Playing a wav file (byte array) using JMF

    Hi,
    I want to play a wav file in form of a byte array using JMF. I have 2 classes, MyDataSource and MyPullBufferStream. MyDataSource class is inherited from PullStreamDataSource, and MyPullBufferStream is derived from PullBufferStream. When I run the following piece of code, I got an error saying "EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7c9108b2, pid=3800, tid=1111". Any idea what might be the problem? Thanks.
    File file = new File(filename);
    byte[] data = FileUtils.readFileToByteArray(file);
    MyDataSource ds = new MyDataSource(data);
    ds.connect();
    try
        player = Manager.createPlayer(ds);
    catch (NoPlayerException e)
        e.printStackTrace();
    if (player != null)
         this.filename = filename;
         JMFrame jmframe = new JMFrame(player, filename);
        desktop.add(jmframe);
    import java.io.IOException;
    import javax.media.Time;
    import javax.media.protocol.PullBufferDataSource;
    import javax.media.protocol.PullBufferStream;
    public class MyDataSource extends PullBufferDataSource
        protected Object[] controls = new Object[0];
        protected boolean started = false;
        protected String contentType = "raw";
        protected boolean connected = false;
        protected Time duration = DURATION_UNKNOWN;
        protected PullBufferStream[] streams = null;
        protected PullBufferStream stream = null;
        protected final byte[] data;
        public MyDataSource(final byte[] data)
            this.data = data;
        public String getContentType()
            if (!connected)
                System.err.println("Error: DataSource not connected");
                return null;
            return contentType;
        public void connect() throws IOException
            if (connected)
                return;
            stream = new MyPullBufferStream(data);
            streams = new MyPullBufferStream[1];
            streams[0] = this.stream;
            connected = true;
        public void disconnect()
            try
                if (started)
                    stop();
            catch (IOException e)
            connected = false;
        public void start() throws IOException
            // we need to throw error if connect() has not been called
            if (!connected)
                throw new java.lang.Error(
                        "DataSource must be connected before it can be started");
            if (started)
                return;
            started = true;
        public void stop() throws IOException
            if (!connected || !started)
                return;
            started = false;
        public Object[] getControls()
            return controls;
        public Object getControl(String controlType)
            try
                Class cls = Class.forName(controlType);
                Object cs[] = getControls();
                for (int i = 0; i < cs.length; i++)
                    if (cls.isInstance(cs))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Time getDuration()
    return duration;
    public PullBufferStream[] getStreams()
    if (streams == null)
    streams = new MyPullBufferStream[1];
    stream = streams[0] = new MyPullBufferStream(data);
    return streams;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.media.Buffer;
    import javax.media.Control;
    import javax.media.Format;
    import javax.media.format.AudioFormat;
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.PullBufferStream;
    public class MyPullBufferStream implements PullBufferStream
    private static final int BLOCK_SIZE = 500;
    protected final ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW);
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM_MS, 8000.0, 8, 1,
    Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
    Format.byteArray);
    private int seqNo = 0;
    private final byte[] data;
    private final ByteArrayInputStream bais;
    protected Control[] controls = new Control[0];
    public MyPullBufferStream(final byte[] data)
    this.data = data;
    bais = new ByteArrayInputStream(data);
    public Format getFormat()
    return audioFormat;
    public void read(Buffer buffer) throws IOException
    synchronized (this)
    Object outdata = buffer.getData();
    if (outdata == null || !(outdata.getClass() == Format.byteArray)
    || ((byte[]) outdata).length < BLOCK_SIZE)
    outdata = new byte[BLOCK_SIZE];
    buffer.setData(outdata);
    byte[] data = (byte[])buffer.getData();
    int bytes = bais.read(data);
    buffer.setData(data);
    buffer.setFormat(audioFormat);
    buffer.setTimeStamp(System.currentTimeMillis());
    buffer.setSequenceNumber(seqNo);
    buffer.setLength(BLOCK_SIZE);
    buffer.setFlags(0);
    buffer.setHeader(null);
    seqNo++;
    public boolean willReadBlock()
    return bais.available() > 0;
    public boolean endOfStream()
    return willReadBlock();
    public ContentDescriptor getContentDescriptor()
    return cd;
    public long getContentLength()
    return (long)data.length;
    public Object getControl(String controlType)
    try
    Class cls = Class.forName(controlType);
    Object cs[] = getControls();
    for (int i = 0; i < cs.length; i++)
    if (cls.isInstance(cs[i]))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Object[] getControls()
    return controls;

    Here's some additional information. After making the following changes to MyPullBufferStream class, I can play a wav file with gsm-ms encoding with one issue: the wav file is played many times faster.
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM, 8000.0, 8, 1,
                Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
                Format.byteArray);
    // put the entire byte array into the buffer in one shot instead of
    // giving a portion of it multiple times
    public void read(Buffer buffer) throws IOException
            synchronized (this)
                Object outdata = buffer.getData();
                if (outdata == null || !(outdata.getClass() == Format.byteArray)
                        || ((byte[]) outdata).length < BLOCK_SIZE)
                    outdata = new byte[BLOCK_SIZE];
                    buffer.setData(outdata);
                buffer.setLength(this.data.length);
                buffer.setOffset(0);
                buffer.setFormat(audioFormat);
                buffer.setData(this.data);
                seqNo++;
        }

  • How to open a byte array of pdf into acrobat reader dynamically..

    hi,
    my java program is connecting to a url and downloading various file(.pdf,.xml format) into hard-disk. now the requirement is if user select "Preview" button, then file is downloaded and opened with appropriate application(acrobat reader for .pdf file) but not saved anywhere in hard-disk ...
    any idea, any hint any help is welcomed..
    thanks in advance..

    hi friends,
    i got the solution. i am using one external api of adobe acrobat, through which i am able to stream pdf document in form of byte array into acrobat viewer,without writing data in any file.
    so my work is done.. :)

  • Byte array to base64encoder problem, cannot encode a 7.7 MB file

    hey guys, so ive been trying to use the base64encoder to encode a bytearray which is then sent thru a webservice to the server to be decoded.
    and as the subject of this post suggests, i have been having problems encoding a big file,
    forexample i tried to upload/convert a 84KB image and it worked just fine... the trace of the string ended with a "==" which i believe means that the conversion is complete...
    but when i try to upload a 7.7MB image, it is, i guess, crashing... i dont see any "==" in the string... so i guess its not working... i was wondering if there is any any type of file size limit or soemthign for the encoding...
    the code i have is
    import flash.events.Event;
    import flash.net.FileFilter;
    import flash.net.FileReference;
    import flash.utils.ByteArray;
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.utils.Base64Encoder;
    import services.images.ImageData;
    import services.images.Images;
    import services.images.ReturnMessage;
    // ActionScript file
        public var fileRef:FileReference = new FileReference();
        public var imgCollection:ArrayCollection = new ArrayCollection();
        public var imgService:Images = new Images();
        public var imageData:ImageData = new ImageData();
        public var returnMsg:ReturnMessage = new ReturnMessage();
        public function onBrowseButtonClicked(event:MouseEvent):void{
            var arr:Array = [];
            arr.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
            fileRef.browse(arr);
            fileRef.addEventListener(Event.SELECT, fileRef_select);
            fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
        public function fileRef_select(event:Event):void{
            fileRef.load();
        public function fileRef_complete(event:Event):void{
            img.source = fileRef.data;
            var fileByteArr:ByteArray = fileRef.data;
            var b64En:Base64Encoder = new Base64Encoder();
            b64En.encodeBytes(fileByteArr);                                                  //<----------------------------------------------------------
            var str:String = b64En.flush();                                                        //<----------------------------------------------------------
            trace(str.length);
            b64En.reset();
            trace("------------------------------------      " + str + "     -----------------------------");
            imageData.Base64EncodedImage = str;
            imageData.FileName = "nameofstring";
            imgService.UploadImage(imageData);
           imgService.addEventListener(FaultEvent.FAULT, servFault);
           imgService.addEventListener(ResultEvent.RESULT, imgServSuccess);
        public function imgServSuccess(event:ResultEvent):void{
            Alert.show("i am in the result");
            returnMsg = event.result as ReturnMessage;
            var resultStr:String = event.result as String;
            Alert.show(resultStr);
            if(returnMsg.ThereWasAnError){
                trace(returnMsg.ErrorMessages.getItemAt(0).toString());
        public function servFault(event:FaultEvent):void{
            Alert.show("2 " + event.fault.message);
            Alert.show("3 " + event.fault.faultCode);
    any help will be greatly appretiated!! thanks in advace!

    yeah i did actually... except i think i changed a LOT of code since i last posted this article...
    so i dont remember where this code is exactly... lol
    i have the following code now...
    hope this helps
    i use a a lot of webservices... so there is some of that code included in there aswell...
    * This file will do the file upload. It has been suggested to me multiple times, that using a queueing system for
    * file upload is not a good idea. Instead I declared a counter and used the final function to fire the next item
    * in the array. this also makes canceling a routine easier.
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.net.FileReference;
    import flash.net.FileReferenceList;
    import flash.utils.ByteArray;
    import mx.collections.ArrayCollection;
    import mx.controls.*;
    import mx.managers.*;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.utils.Base64Decoder;
    import mx.utils.Base64Encoder;
    import services.images.Images;
    import valueObjects.*;
        public var t:Number = 0;
        public var fileRef:FileReferenceList = new FileReferenceList();
        public var listCacheFiles:Array = new Array();
        [Bindable] public var fileListArr:Array = new Array();
        [Bindable] public var fileNames:ArrayCollection = new ArrayCollection();
        [Bindable] public var arrUploadFiles:Array = new Array();
        public var file:FileReference;
        public var _numCurrentUpload:Number = 0;
        public var imageData:valueObjects.ImageData;
        public var imageService:Images = new Images();
        public var saveImages:Images;
        public var returnMsg:ReturnMessage = new ReturnMessage();
        public var dataToSave:ImageData;
        public var myCounter:int = 0;
        public var numPerc:Number;
        /*vars to possible delete*/
        public var fileListx:ArrayCollection;
         * Initiates the browse, when files are selected the selectionHandler function is called
        public function initiateBrowse():void{
            var filter:Array = [];
            filter.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
            fileRef.addEventListener(Event.SELECT, selectionHandler);
            fileRef.browse(filter);
         * selection handler takes the selected files and puts them in 2 different arrays
         * fileListArr contains all the file information like the image itself and the name and everything
         * fileNames contains the information essential to populate the datagrid in the cropper.mxml
        public function selectionHandler(event:Event):void{
            //trace("selection Handler ->>");
            fileRef.removeEventListener(Event.SELECT, selectionHandler);
            var numSelected:int = event.target.fileList.length;
            var fileList:Array = event.target.fileList;
            fileListx = new ArrayCollection();
            fileListx = event.target.fileList as ArrayCollection;
            //var oldListLength:Number = fileListArr.length;
            for each(var item:Object in fileList){
                fileListArr.push(item);
                fileNames.addItem({
                    num: fileNames.length + 1,
                    name: item.name,
                    size: formatFileSize(item.size),
                    status: "",
                    itemDetails: item
            var newListLength:Number = fileListArr.length;
            if(myCounter > 0)
                loopList(myCounter);
            else
                loopList(0);
         * this function starts one, new filereference for each files in the array
        public function loopList(value:int):void{
            //trace("looplist -->");
            if(value < fileListArr.length){
                _numCurrentUpload = value;       
                file = new FileReference();
                file = FileReference(fileListArr[value]);;
                file.addEventListener(Event.COMPLETE, loadImage);
                file.addEventListener(ProgressEvent.PROGRESS, fileProgress);
                file.load();
         * This function will convert the byte array into a string, and then it sends it to the server.
        public function loadImage(event:Event):void{
            trace("loadImage -->");
            file.removeEventListener(Event.COMPLETE, loadImage);
                myCounter += 1;
                var fileByteArr:ByteArray = event.target.data;
                var b64En:Base64Encoder = new Base64Encoder();
                b64En.encodeBytes(fileByteArr);
                var str:String = b64En.flush();
                imageData = new ImageData();
                imageData.Base64EncodedImage = str;
                imageData.FileName = event.target.name;
                trace("sending -->>  " + imageData.FileName);
                updateStatus("Sending to server");
                imageService.addEventListener(ResultEvent.RESULT, imgServSuccess);
                imageService.UploadImage(imageData);
                b64En.reset();
         * This function will decode the information recieved back from the server.
        public function imgServSuccess(event:ResultEvent):void{
            trace("imgServSuccess -->");
            imageService.removeEventListener(ResultEvent.RESULT, imgServSuccess);
            var returnedImageId:ArrayCollection = new ArrayCollection();
            returnMsg = event.result as ReturnMessage;
            var returnedData:Object = event.result.Images;
            var imgD:ImageData = new ImageData();
            if(returnMsg.ThereWasAnError){
                trace(returnMsg.ErrorMessages.getItemAt(0).toString());
            else{
                for each(var imgData:ImageData in returnedData){
                    var decoded:Base64Decoder = new Base64Decoder();
                    decoded.decode(imgData.Base64EncodedImage);
                    var byteArr:ByteArray = decoded.toByteArray();
                    //img.source = byteArr;
                dataToSave = new ImageData();
                dataToSave = returnedData[0];
                listCacheFiles.push(dataToSave);
                updateStatus("Item in Cache");
                //uploadDetails.visible = true;
                loopList(myCounter);
        public var win:itemDetails;
        public function itemClicking(event:Event):void{
            var fileName:String = event.currentTarget.dataProvider[0].name;
            for(var i:Number = 0; i < listCacheFiles.length; i++){
            //var temp:ImageData = event.target as ImageData;
            win = null;
            win = itemDetails(PopUpManager.createPopUp(this, itemDetails, true));
            win.title = "Enter Details";
            PopUpManager.centerPopUp(win);
            win["save"].addEventListener("click", popupClosed);
        public function popupClosed(event:Event):void{
            var returnedData:ImageData = new ImageData;
            returnedData = win.dataToSave;
            saveImgAndData(returnedData);
        public function saveImgAndData(data:ImageData):void{
            saveImages = new Images;
            saveImages.showBusyCursor = true;
            saveImages.addEventListener(ResultEvent.RESULT, savedSuccess);
            saveImages.addEventListener(FaultEvent.FAULT, faultFunc);
            saveImages.SaveUploadedImageInformation(data);
        public function faultFunc(event:FaultEvent):void{
            Alert.show(event.fault.message);
            Alert.show(event.fault.faultString);
        public function savedSuccess(event:ResultEvent):void{
            //trace("savedSuccess -->");
            var retMsg:Object = event.result.Images;
            //trace("saving -->> " + retMsg[0].FileName);
            updateStatus("Completed");
            //loopList(myCounter);
        private function formatFileSize(numSize:Number):String {
            var strReturn:String;
            numSize = Number(numSize / 1024);
            strReturn = String(numSize.toFixed(1) + " KB");
            if (numSize > 1024) {
                numSize = numSize / 1024;
                strReturn = String(numSize.toFixed(1) + " MB");
                if (numSize > 1024) {
                    numSize = numSize / 1024;
                    strReturn = String(numSize.toFixed(1) + " GB");
            return strReturn;
        public function removeFiles():void{
            var arrSelected:Array = displayFilesList.selectedIndices;
            if(arrSelected.length >= 1){
                for(var i:Number = 0; i < arrSelected.length; i++){
                    fileNames[Number(arrSelected[i])] = null;
                var idx:int = 1;
                for(var j:Number = 0; j < fileNames.length; j++){
                    if(fileNames[j] == null){
                        fileNames.removeItemAt(j);
                        j--;
                    }else{
                        fileNames[j].num = idx++;
                if(fileNames.length > 0)
                    displayFilesList.selectedIndex = 0;
                else
                    displayFilesList.selectedIndex = -1;
                _numCurrentUpload--;
                updateProgBar();
        private function updateStatus(status:String, index:Number = -1):void{
            index = _numCurrentUpload;
            fileNames[index].status = status;
            displayFilesList.invalidateList();
        public function fileProgress(event:ProgressEvent):void{
            //trace("fileProgress -->");
            var numPerc:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
            updateStatus("Uploading: " + numPerc.toString() + "%");
            updateProgBar(numPerc);
            var evt:ProgressEvent = new ProgressEvent("uploadProgress", false, false, event.bytesLoaded, event.bytesTotal);
            dispatchEvent(evt);
        public function updateProgBar(numPerc:Number = 0):void{
            //trace("updateProgBar -->");
            var strLabel:String = (_numCurrentUpload + 1) + "/" + fileNames.length;
            progBar.label = strLabel;
            progBar.setProgress(_numCurrentUpload + numPerc / 100, fileNames.length);
            progBar.validateNow();

  • 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.

  • How to Read Java Byte Array back into SAP xstring Table?

    Hi Guys,
    I have a situation whereby a user can upload a document in a WebDynpro Java Application.  This needs to be saved.  I am trying to see if I can make the location of this file that is being saved to be on our SAP AS.  I have written a SAP RFC that is imported into the Java Application for use.
    The RFC is expecting a table of type TBL1024 which is basically a table of xstring values.  The Java proxy interprets this SAP table as a byte array.  This is my problem... I cannot seem to "break" up the Byte array into lines of 1024 lengt and send it back to SAP.  All that is happening currently is that the byte array creates a singe line in the TBL1024 that consists of only the first 1024 bytes in the array...  This means that only the first 1024 bytes of my document is being saved - making it corrupt.
    Please advise,
    Kind regards,
    Christiaan

    Loop it...
    File file = new File("java.pdf");
    FileInputStream fis = new FileInputStream(file);
    byte[] buf = new byte[1024];
            try {
                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    // Here populate the RFC table               
            } catch (IOException ex) {

  • Unable to merge two byte arrays

    Hi there,
    I am trying to merge two byte arrays into one byte array
    and write into a new word document using OutputStream object.
    But in the new word document that is created only the contents
    of the first byte array are being shown and not that of the second one.
    I have pasted the code below.
    Any pointers will be of great help.
    Thanks and Regards,
    Partha.
    package com.cisco.asit.icn.common.servlets;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import org.apache.poi.hwpf.HWPFDocument;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    public class TestPOC {
         public static void main(String[] args) {
              try
                   System.out.println("I am here...");
                   System.out.println("I am in example 4...");
                   byte[] byteAr1 = getBytesFromFile(new File("c:\\Testing_POC\\Not_blank.doc"));
                   System.out.println(byteAr1.toString());
                   System.out.println();
                   byte[] byteAr2 = getBytesFromFile(new File("c:\\Testing_POC\\Quest.doc"));
                   byte[] finalOne = concatenate(byteAr1, byteAr2);
                   System.out.println("byte array 1..."+ byteAr1.length);
                   System.out.println("byte array 2..."+ byteAr2.length);
                   System.out.println("Final byte array ..."+ finalOne.length);
                   InputStream is = new ByteArrayInputStream(finalOne);
                   POIFSFileSystem fss = new POIFSFileSystem(is);
                   OutputStream out1 = new FileOutputStream("c:\\Testing_POC\\Result.doc");
                   fss.writeFilesystem(out1);
                   System.out.println("Stored to file system...");
                   try {
                        Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL \"" + "c:\\Testing_POC\\Result.doc");
                   catch (IOException e1){
                        e1.printStackTrace();
                   System.out.println("I am fine till here...");
         out1.flush();
         out1.close();
         catch (Throwable t) {
         t.printStackTrace();
         byte[] res = new byte[l.length + r.length];
         System.arraycopy(l, 0, res, 0, l.length);
         System.arraycopy(r, 0, res, l.length ,r.length);
    return res;
         public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);
    // Get the size of the file
    long length = file.length();
    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
    // File is too large
    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];
    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
    && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
    offset += numRead;
    // Close the input stream and return bytes
    is.close();
    return bytes;
    }

    parthInfy wrote:
    Hi there,
    I am trying to merge two byte arrays into one byte array
    and write into a new word document using OutputStream object.
    But in the new word document that is created only the contents
    of the first byte array are being shown and not that of the second one.
    Because the end of the first byte array contains a "document ending" tag and anything after that is just flotsam. And, even if you could remove that "document ending" tag, there is for the second a "document begin" tag. (Among many other tags and flags in both documents.) Word (ar just about any) documents are not simple text files to be concatented, truncated, twisted, inverted, or whatever else, at your pleasure. You actually, God forbid, have to kinow what you're doing, to manipulate them at this level. And, surprise, surprise, you don't.
    Edit: Google "POI"

Maybe you are looking for

  • Help needed for grouping.

    Hi,     Help needed . I have an internal table having 6 . Ex : f1     f2    f3     f4    f5    f6 a     aa    11    p1  10    10 a     aa    12    p1  20    20 b     aa    11    p2  30    30 b     aa    12    p2  40    30 Now i want to sum the fields

  • Upgrading an IMac G5 OSX 10.3.9 from Panther to Leopard?

    I have been given contradictory info from the Apple sales dept. I have been told I could upgrade to Leopard...and that I could only use Tiger. What is the truth? My Safari quits frequently and I can not interface with some websites properly. So not s

  • Missing Document Number Report in Oracle Accounts Payable

    Hi All, Can you please let me know if there alternative report for Missing Document Number Report in R12...... similar to what we had in 11.5.9 Instance In AP Thanks Edited by: user5358827 on Apr 19, 2010 11:31 AM

  • Ora 8i and Dev 6.0.0.0

    I have installed Oracle 8i Server on ... a server (Win 2000) and Oracle 8i Client on ... a client (Win 2000). Oracle_home set by default : OraHome81, ok, all works fine. Now I try to install Developer 6.0.0.0 (NT). I cannot give any Oracle Home : - O

  • How to enabale trace in Easy DMS ?

    Hi, I used BADI: DOCUMENT_MAIN01 & method: ASSIGN_NUMBER to assign document number. Now am creating document through Easy DMS am getting error "Exception Occurred". How can i find, where is the problem ? How can i enable Trace option in Easy DMS ? I