Java writing out bytes from one file, reading back in again

Hi, I'm having some trouble with bytes.
I have one program which outputs the following bytes into a file (using Printstream.write() - I'm sure that this program is working fine):
4 0 64 0 4 0 128 0 63 223 64 20 4 16 130 0 60 16 64 1 63 223 79 236 64 16 195 232 116 63 255 232 148 0 0 0
I'm then reading in the bytes using the code given on this page (http://www.exampledepot.com/egs/java.io/File2ByteArray.html)
and I get...
4 0 64 0 4 0 -128 0 63 -33 64 20 4 16 -126 0 60 16 64 1 63 -33 79 -20 64 16 -61 -24 116 63 -1 -24 -108 0 0 0
As you can see I now have negative numbers - I noticed that if I do 256 + (the negative number) then i get the number I originally wrote out
I tried fixing this when I read in by doing
bytes[i] = (byte) (256 + bytes);
but it doesn't change anything
how can I either change it so it reads in the bytes exactly as i wrote them out, or write a bit of code that takes the negatives and converts them to the original positives?
thx

Unconditional wrote:
Integer x1 = (bytes[i] << 24) & 0xFF;
                  Integer x2 = (bytes[i+1] << 16) & 0xFF;
                  Integer x3 = (bytes[i+2] << 8) & 0xFF;
                  Integer x4 = (bytes[i+3] << 0) & 0xFF;is what I'm doing
System.out.println("x1 " + x1 + " x2 " + x2 + " x3 " + x3 + " x4 " + x4);
returns
x1 0 x2 0 x3 0 x4 0
x1 0 x2 0 x3 0 x4 4
x1 0 x2 0 x3 0 x4 0
x1 0 x2 0 x3 0 x4 128
x1 0 x2 0 x3 0 x4 0
x1 0 x2 0 x3 0 x4 63
x1 0 x2 0 x3 0 x4 223
x1 0 x2 0 x3 0 x4 64
x1 0 x2 0 x3 0 x4 20What are you trying to do? Combine the bytes into an int?

Similar Messages

  • Is it possible to compile & run other java files from one file

    hi friends,
    i need to run 2,3 java sourse files(first.java,second.java etc) from one file.i tried the Runtime.getRunTime().exec( cmd) but here cmd must be a executable file
    what is need is to compile and run the files (first.java,second.java) from one other source file
    pls. help me in this matter,
    with warm regards,
    Vishal

    Sure:public class Test {
       public static void main(String[] args) {
          try {
             Runtime r = Runtime.getRuntime();
             r.exec("javac Test2.java");
          } catch (Exception e) {
    public class Test2 {
       public static void main(String[] args) {
          System.out.println("Hello World!");
    }Note that Test and Test2 are in two seperate files.

  • How to read a byte[] from a file

    Hi can someone help me to read a byte[] from a file. I need to save a byte[] to a file and then retrieve it later can someone help in this..
    Thanx

    there are actually docs on the classes ByteArrayInputStream and ByteArrayOutputStream here:
    http://java.sun.com/javase/6/docs/api/
    go there (copy & paste in browser) and text search for the above classes.
    Then read into it. That way, you will come to a better comprehension of the entire thing. You may as well want to read this:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    And for the future: if you have general problems, search API docs and tutorials first and solve them yourself. The guys around here can get pretty annoyed about "Teach me the entire Java Thing" (also called "someone do my homework") requests.
    If you have a special problem, ie an Exception you don?t understand or a method wich you don?t know how it works, everybody will like to help you.
    Only few real serial killers frequent these forums.

  • Howto make created folders/ files from one teacher, read only for other teachers?

    Hello there,
    as an admin @ school I was wondering how to make created folders/ files from one teacher, read only for other teachers?
     - In a 2008domain, created a group "teachers"
     - created a folder "teacher data" where all teachers have read/write permissions
    ideal,a teacher who make's a folder in "teacher data" should be the only oen who is able to add file's to that folder and dele that folder or files. Other teachers may be able to read the content of the folder.
    Is this possible to set up and how?
    many thanks.
    Nico.
    rds

    Hi Nico,
    You could set the permissions below to resolve the issue:
    For the root folder "teacher data": give the full control permission to CREATOR OWNER – "Subfolders and files only" and give the read/write permissions to the group "teachers"– "This folder only".
    Best Regards,
    Mandy 
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Error 105, Could not read full block (2048 bytes) from checkpoint file ~/dirchk/sdfsdj.cpe

    Hi expert,
        i am getting below error in goldengate  due to mount point full and i released the space and still the same error for all gg processes. i can see the *cpe cpr file become 0 bytes. so i deleted and re added the extract and repliacat and while adding the replcat i used add replicat  checkpoint table because of that multiple entries of same replicat came in checkpoint table . my checkpoint details also  present in ./GLOBALS. now my doubt is if add  replicate with mentioning checkpoint table name  will duplicate entry will be created or what is the work around for this.
    MANAGER RUNNING
    Invalid checkpoint for EXTRACT  qqqq   (error 105, Could not read full block (2048 bytes) from checkpoint file XXXXXXXXX)
    Invalid checkpoint for EXTRACT  qqq(error 105, Could not read full block (2048 bytes) from checkpoint file XXXXXXXXXX)
    Invalid checkpoint for REPLICAT qqq  (error 105, Could not read full block (2048 bytes) from checkpoint file XXXXXXXXXXX)

    Hi Kariyath
    Increase the page size of your windows machine.Check for the recommanded page size.Remember that the recommanded page size should be the lower limit.If you have any issue feel free to ask.Your prob will be solved
    Award suitable points

  • Writing multiple images to one file using ImageIO

    I am having trouble saving and reading multiple images from to/from one file. Here is the best i can come up with:
    //this is utilizing an ObjectOutputStream because i need to also save some objects to the file
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\images.dat"));
    oos.writeInt(ImageTable.size());
    for(int k = 0; k  < ImageTable.size(); k++)
        ImageIO.write((BufferedImage)ImageTable.get(k), "png", oos);
        oos.flush();
    //////////////////////////read function/////////////////////////
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\images.dat"));
    int size = ois.readInt();
    for(int k = 0; k < size; k++)
        ImageTable.add(ImageIO.read(ois));
    }What it seems to do is read the first image and then place the marker at the end of the file so each consecutive calls to reading the file end up in either null, -1, or an EOF exception (bleh). Does anyone know how i can do this properly?
    The code does run and saves something, although it is hard to tell exactly what it is saving since it is all in png format, it also loads the first image properly.

    Is it possible to pack the different images in one big image?Conversely, some image formats let you store multiple images in a single image file.
    Here's a demo. My results are that I don't have a gif writer, tiff can write sequences (this
    is a well-known tiff property), I can trick (?) jpeg into stroring multiple images and I
    can't get png to work: three images go in, one comes out.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    import java.util.List;
    public class MultiImageTest {
        public static void main(String[] args) throws IOException {
            URL url1 = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
            URL url2 = new URL("http://today.java.net/jag/bio/JAG2001small.jpg");
            URL url3 = new URL("http://today.java.net/jag/Image24-small.jpeg");
            BufferedImage[] images = {ImageIO.read(url1), ImageIO.read(url2), ImageIO.read(url3)};
            display(images, "original", 0, 0);
            String[] suffixes = {"gif", "jpeg", "png", "tiff"};
            int x = 30, y = 20;
            for(int j=0; j<suffixes.length; ++j) {
                String suffix = suffixes[j];
                try {
                    writeFile(images, suffix);
                    display(readFile(suffix), suffix, x, y);
                    x += 30;
                    y += 20;
                } catch (Exception e) {
                    System.err.println(suffix + ": " + e.getMessage());
        static void writeFile(BufferedImage[] images, String suffix) throws IOException {
            Iterator ws = ImageIO.getImageWritersBySuffix(suffix);
            if (!ws.hasNext())
                throw new IOException("no writer for: " + suffix);
            ImageWriter w = (ImageWriter) ws.next();
            File file = new File("temp." + suffix);
            file.delete();
            w.setOutput(ImageIO.createImageOutputStream(file));
            if (w.canWriteSequence()) {
                System.out.println("Using writeToSequence for format " + suffix);
                w.prepareWriteSequence(null);
                for(int j=0; j<images.length; ++j)
                    w.writeToSequence(new IIOImage(images[j], null, null), null);
                w.endWriteSequence();
            } else {
                System.out.println("cross fingers for format " + suffix);
                for(int j=0; j<images.length; ++j)
                    w.write(images[j]);
        static BufferedImage[] readFile(String suffix) throws IOException {
            Iterator rs = ImageIO.getImageReadersBySuffix(suffix);
            if (!rs.hasNext())
                throw new IOException("no reader for: " + suffix);
            ImageReader r = (ImageReader) rs.next();
            File file = new File("temp." + suffix);
            if (!file.exists())
                throw new IOException("no file: " + file.getName());
            r.setInput(ImageIO.createImageInputStream(file));
            List images = new ArrayList();
            for(int j=0; true; ++j) {
                try {
                    images.add(r.read(j));
                } catch (IndexOutOfBoundsException e) {
                    break;
            return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
        static void display(BufferedImage[] images, String title, int x, int y) {
            JPanel cp = new JPanel(new GridLayout(1,0));
            for(int j=0; j<images.length; ++j)
                cp.add(new JLabel(new ImageIcon(images[j])));
            JFrame f = new JFrame(title);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(cp));
            f.pack();
            f.setLocation(x, y);
            f.setVisible(true);

  • Passing Value from one File to Another !!!

    Hi Friends,
    I have an issue, I have two different Swing programs (two seperate java files). I want to transfer value from one file to the another. Like we do in Servlets or JSP, we use sessions or Hiddenfields. The same way I want to retriev value in a new file from a previous one.
    Hope that all u champs out there have the answer to my query.
    Thanks,
    [email protected]

    This is a B2B comms question...
    A quick and dirty method is to use Socket/ServerSocket and use a basic protocol to do the transfer, if you are feeling heroic then use XML as the message format...
    A lot depends on whether your applications are running on separate boxes, i.e. do you need to communicate across a network...
    If not, if they are always going to be on the same "box" then you could just use well-known places for files...not portable but effective...

  • A way to move layers from one file to another in actions?

    Ok, question for the gurus out there - rather than try to explain, I'll give you an example: Lets say I have a series of adjustment layers that I want to apply to a sequence of 40 images. The adjustments are in a layer group, and are saved as a separate file.
    I DON'T want to drag and drop them, I want to run an action that will copy the adjustments to each image- now I know I can save down each adjustment as a separate file, lets a curve (acv) a selective color (ahu) file and load THAT in as part of my action. But I don't want to do that either, because these adjustments will change and I want to easily re-render my changes on all 40 images in one step.
    I also don't want to use After Effects to do it, because my client doesn't own it. There used to be
    a way to move layers from one file to another in actions because I seem to remember doing it. The answer is not Duplicate Group either because that needs you to specify a destination file name.
    Is it possible to do this without scripting? I'm pretty sure it used to be because I seem to remember doing it, just cant remember HOW I did. Maybe I'm wrong about this though.
    Thanks and sorry for the long post, this has been baffling me for weeks.

    Thanks Ed, but as I explained above
    "I know I can save down each adjustment as a separate file, lets a curve (acv) a selective color (ahu) file and load THAT in as part of my action. But I don't want to do that either"
    What I want to know is is there a way to move adjustment layers from one file to another in an action. I know also that you can use the clipboard to move pixel layers, but I've yet to find a way to move adjustments.

  • I dragged a cut out image from one photoshop document into another and now it is blurry. What to do?

    I dragged a cut out image from one photoshop document into another and now it is blurry. What can I do to prevent this?

    What is the resolution of the image that you "dragged"? The resolution is the number in pixels per inch (ppi). If you dragged a significantly lower resolution file into a higher resolution file, it could result in a blurry image.
    see below:
    For further reading of Key Concepts:
    http://www.adobe.com/designcenter-archive/keyconcepts/articles/concept_resolution.html
    You can determine the image size by choosing Image > Image Size
    below you can see the pixel dimensions of my example image.
    Resolution Basics:
    Adobe TV- http://tv.adobe.com/watch/creative-sweet-tv/photoshop-resolution-basics/
    http://tv.adobe.com/watch/visual-design/getting-started-09-resizing-an-image/
    Adobe Help:
    http://help.adobe.com/en_US/photoshop/cs/using/WSfd1234e1c4b69f30ea53e41001031ab64-7945a.h tml
    -janelle

  • Drag and drop picture frames in Photoshop Elements 11 from one file to another?

    Hello,
    I am a digital scrapbooker.
    I recently started using Adobe Photoshop Elements 11. I previously had been using Elements 7. I make extensive use of Picture Frames i.e "Basic Black 10px", and in Elements 7, it was very easy to drag and drop a picture frame from one file to another. (I use a separate file for each scrapbook page, and I often move pictures between  pages as I scrap them)
    In Photoshop Elementa 11,  I can drag and drop a picture frame from one file to another, but ONLY if there is no picture in it. If there is a picture, I cannot drag and drop - the circle-slash icon appears showing that it won't land. I was able to do this in Photoshop Elements 7, whether or not there was a picture in the frame.
    Any ideas of what I might be doing wrong, or did Photoshop Elements change this functionality?
    Thank you!

    I think this might be a bug in pse 11, at least on the windows version.
    You might try right clicking on the frame layer in the layers panel, choose Duplicate Frame Layer and pick your other document as the destination.

  • HELP: Copying layers from one file to another to keep structure not possible??!!!

    Hi guys,
    I have a curious question. Sounds a bit silly and highly disappointed if Illustrator is actually not capable of doing this. Hopefully I have missed something.
    I have an AI doc that has grown so large that saving it now is a major effort so trying to break out sections into multiple AI files. Allot of users will be working on these files so it is imperative that all the Artboard elements are clearly organized in the appropriate folders (layers). Im trying to simply copy and paste a layer that has multiple layers beneath and within those more layers to another empty AI file. Everything copies correctly and in place however it dumps all the elements into a single massive layer in the new file. If I go into the Layer Palette menu and check on Paste Remembers Layers it does a better job at keeping some of the structure but it still doesnt copy exactly how the structure was in the Master document.
    Please tell me Im doing something wrong. I cant believe that you cant simply drag and drop a parent layer from one file to another while maintaining its structure! Exactly like in Photoshop - copying a folder from one file to another is simply as easy as dragging and dropping ...is this same methodology not available with Illustrator? I always assumed the layer and folder concept between these two packages were somewhat interchangeable.
    Thanks for any help, comments, or suggestions
    Nick.

    Hi All,
    After much trial and error trying to locate where the problem was it ended up being the guide objects. If you have the guides set to lock and attempt to copy out any layer that a guide is sitting in the resulting copy/paste will break apart that layer structure in the destination file. Simply setting the guides unlock allows everything to translate correctly.
    You guys may have known about it already but I learnt a little something in the process. Thanks to all for your suggestions!
    Cheers

  • Colors get desaturated when picked and transferred from one file to the other! Why?

    I used the color picker tool to choose colors from one file and fill it in another file. The color shows as desaturated when the other file is active. Both files are on the exact same settings, but I don't know what is happening. I reset the tools. But nothing.

    Are you sure that mode (RGB, CMYK, etc) and assigned color profiles is the same on both files?
    May be you turn on Proof Privew (Ctrl-Y) on one of the files.
    PS. my english is poor )

  • I wish to link a  cell from one file or "shell" with a specific quantity to another cell in another file or "shell".

    I wish to link or send a  cell from one file or "shell" with a specific quantity or text to another cell in another file or "shell".  For example.  I wish to  send all general ledger (one data enty File or "sheet")  entries into their specific individual accounts. (in seperate files or "sheets").   Is this possible in Numbers?

    Hi cochise0011;
    A picture of tables would be much easier to comprehend the querry.
    Regards,

  • How can I script moving paths from one file to another?

    Hello. I have 1 image with various color correction layers. The other is the exact same size but only contains paths. How can I script moving paths from one file to another? Thanks, in advance, for any help you can offer. Thanks!

    Thanks! This one actually worked for me. Thanks for your help.
    http://forums.adobe.com/message/3305389#3305389

  • How to transfer the tables from one file group to another file group in SQL 2008.?

    Hello all,
    I have few issues regarding the transfer of the tables from one file group to another file group  in SQL 2008 and also How can we  backup
    and restore the particular database based on file group level.
    Let’s say I have a tables stored within the different FG. such as
    Tables                                                    
      File group
    Dimension tables                                              
                                                                     Primary
    Fact tables                                               
                                                                              FG1
               FG2…
    zzz_tables                                               
                                                                              DEFAULT_FG    
    dim.table1                                                                                                                          DEFAULT_FG
    dim.table2                                                                                                                          DEFAULT_FG
    Here all I want to transfer the dim.table1 ,dim.table2  from  DEFAULT_FG to the Primary File
    group .So is there simple methods for transfer the dim.table1,2  from one FG to another .I have tried somewhat but I couldn’t get the exact way .So if someone have better idea please share your knowledge that would be really appreciated.
    Secondly after moving those dim.table1 ,dim.table2 from DEFAULT_FG to Primary ,All I want to backup and restore the database only containing  the Primary and FG1,FG2… not
    a DEFAULT_FG.Is it possible or not.?
    Hope to hear from the one who knows better approach for this kind of task .Your simple help will be much appreciated.
    Regards,
    Anil Maharjan

    Well after all my full day research on this topic had paid off, I finally got the solution and am so happy to research on these things. It makes
    us feel really happy after all our research and hard work doesn't goes as waste.
    Finally I got what I am looking for and want to make sure that I am able to transfer the tables from DEFAULT_FG to another FG without tables
    having clustered index on that tables .
    With the help of the link below I finally got my solution where Roberto’s coded store procedure simply works for this.
    Really thanks to him for his great post and thanks to all for your response and your valuable time.
    http://gallery.technet.microsoft.com/scriptcenter/c1da9334-2885-468c-a374-775da60f256f
    Regards,
    Anil Maharjan

Maybe you are looking for