Binary files in java

hi
I am a bit new to java and am having some problems with binary files. What I need to do is search a binary file for any accurances of the data contained with in another set of binary files. I need to know if the first file contains any of the signatures in the set of files. any help would be great.
thanks very much
Colin

you take your file, you read in some bytes and you loop thru those bytes to find matching bytes that you are looking for. Here's some cdoe that's probably not as elegant as it could be, but you get what you pay for.
public static int indexOf(byte[] a, byte[] b) {
   return indexOf(a, b, 0);
public static int indexOf(byte[] a, byte[] b, int start) {
   if(a == null || b == null || a.length == 0 || b.length == 0 || a.length < b.length) {
      return -1;
outer:   for(int i = start; i < a.length-b.length; i++) {
      if(a[i] == b[0]) {
         for(int j = 0; j < b.length; j++) {
            if(a[i+j] != b[j]) {
               break outer;
         return i;
}

Similar Messages

  • Read binary file in java

    To read a text file i used
    FileReader reader=new FileReader("d:/a.txt");
    please guide me on how to read a binary file in java
    Any input would be greatly appreciated!
    Thanks in advance!
    Edited by: nikkj on Aug 7, 2010 7:36 PM

    I'll give you the quick answer: you use Readers for character streams (e.g., text files) and InputStreams for binary streams (e.g., binary files).
    Still, read the tutorial. You will find out lots of useful info.

  • Creating Binary Files in Java

    Does anyone know how to create a binary file in Java.
    in C i can do an fopen("filename" , "rb") i cannot find a equivalent java binary file stream.
    Thanks

    The following code is part of my FileIO applet. This method allows the user to download any file from my server and save it on his/her disk, the download is accomplished by doing a byte-read and byte-write (byte mover as I'd call it). This example illustrates how you can read and write binary files in Java:
       public void aok_DownLoad(String inputFile, String outputFile) {
          try {
             URL url=new URL(inputFile);
             InputStream in;
             in=url.openStream();
             BufferedInputStream reader=new BufferedInputStream(in,4096);
             FileOutputStream out=new FileOutputStream(outputFile);
             BufferedOutputStream writer=new BufferedOutputStream(out,4096);
             byte[] buf=new byte[4096];
             int byteRead;
             while ((byteRead=reader.read(buf,0,4096))>=0) {writer.write(buf,0,byteRead);}
             reader.close();
             writer.flush();
             writer.close();
          catch (Throwable exception) {
             exception.printStackTrace();
       }V.V.
    PS: in this posting the code is posted in a different manner so that the > sign is not converted to & gt ; by the forum's software

  • DE PDP-1 binary file from Java

    Can someone here help me, please!?
    Anyone know how to convert a Java class file into a binary file that will run natively on my Digital PDP-1 computer? I just spent over $120,000 for it! Thanks.
    This resurrected thread was first posted November 25, 1960 at 8:25AM
    -------------------------------------------------------------------------

    This resurrected thread was first posted November 25,
    1960 at 8:25AMIn what time zone?

  • Need to create a function to receive binary files from Java WebDynpro

    Hey,
    I need to recieve files from java Webdynpro and save them as a file on the backend
    system. After that, the file will be loaded to the documentum.
    In a function module, I only can get the files as a String. Therefore (I think), I need the
    binary file as base64 encoded. Otherwise I can´t get it as a string.
    Now I need to decode it in the backend, but how? I know, there are HTTP-classes
    in newer system, but not in the 4.6C System, I have here.
    Any idea, how I can recieve the files in the function module and transfer it as binary
    file to the backend system?
    If I load a file from the gui with gui_upload, I get the binary file as an internal table
    and can transfer it to the backend filesystem now. Maybe I can get the binary file
    in this way in the function?
    Thank You for Your help!
    Arne

    http://jakarta.apache.org/commons/net/

  • JNI Invocation: open file in Java, write file in CPP

    Hello,
    Warning: I am a dunce, bad CPP code ahead!
    Using JNI invocation, I am trying to read a binary file in Java and write it in CPP.
    Everything compiles and runs without error, but the input and output jpg files are of course different.
    TIA to any help,
    kirst
    (begin ByteMe.java)
    import java.io.*;
    public class ByteMe
        // Returns the contents of the file in a byte array.
        public byte[] getBytesFromFile(String strInfo) throws IOException
            System.out.println("Testing:" + strInfo);
            File file = new File("1.jpg");
            InputStream is = new FileInputStream(file);
            // Get the size of the file
            long length = file.length();
            // 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;
            // Ensure all the bytes have been read in
            if (offset < bytes.length)
                throw new IOException("Could not completely read file "+file.getName());
            // Close the input stream and return bytes
            is.close();
            return bytes;
        public ByteMe()
              //System.out.println("in constructor");
    }(end ByteMe.java)
    (begin ByteMe.cpp)
    #include <stdlib.h>
    #include <string.h>
    #include <jni.h>
    #include <windows.h>
    // for file operations:
    #include <fstream>
    int main( int argc, char *argv[] )
         JNIEnv *env;
         JavaVM *jvm;
         JavaVMInitArgs vm_args;
         JavaVMOption options[5];
         jint res;
         jclass cls;
         jmethodID mid;
         jstring jstr;
         jobject obj_print;
         options[0].optionString = "-Xms4M";
         options[1].optionString = "-Xmx64M";
         options[2].optionString = "-Xss512K";
         options[3].optionString = "-Xoss400K";
         options[4].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
         vm_args.nOptions = 5;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         // Create the Java VM
         res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         if (res < 0)
              printf("Can't create Java VM");
              goto destroy;
         cls = env->FindClass("ByteMe");
         if (cls == 0)
              printf("Can't find ByteMe class");
              goto destroy;
         jmethodID id_construct = env->GetMethodID(cls,"<init>","()V");
         jstr = env->NewStringUTF(" from C++\n");
         obj_print = env->NewObject(cls,id_construct);
         // signature obtained using javap -s -p ByteMe
         mid = env->GetMethodID(cls, "getBytesFromFile", "(Ljava/lang/String;)[B");
         if (mid == 0)
              printf("Can't find ByteMe.getBytesFromFile\n");
              goto destroy;
         else
              jbyteArray jbuf = (jbyteArray) env->CallObjectMethod(obj_print,mid,jstr);
              jlong size = jsize(jbuf);
              printf("size is: %d\n", size); // size shown in output is
              std::ofstream out("data.jpg", std::ios::binary);
              out.write ((const char *)jbuf, 100000);     
         destroy:
             if (env->ExceptionOccurred())
                env->ExceptionDescribe();
        jvm->DestroyJavaVM();
    }(end ByteMe.cpp)

    Hello,
    Me again. Well, not such a dunce after all. Here is code that works correctly, and compiles with no errors and no warnings.
    Will much appreciate help with clean-up code.
    TIA,
    kirst
    (begin ByteMe.java)
    import java.io.*;
    public class ByteMe
        public long getFilezize(String strInfo) throws IOException
              // demonstrates String parameter passed from CPP to Java:
              System.out.println("(getFilesize) Hello world" + strInfo);
              File file = new File("1.bmp");
              InputStream is = new FileInputStream(file);
              // Get the size of the file
              long length = file.length();
              is.close();
              return length;
        // Returns the contents of the file in a byte array.
        public byte[] getBytesFromFile(String strInfo) throws IOException
            System.out.println("(getBytesFromFile) Hello world" + strInfo);
            File file = new File("1.bmp");
            InputStream is = new FileInputStream(file);
            // Get the size of the file
            long length = file.length();
            System.out.println("length is: " + String.valueOf(length));
            // 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;
            // Ensure all the bytes have been read in
            if (offset < bytes.length)
                throw new IOException("Could not completely read file "+ file.getName());
            // Close the input stream and return bytes
            is.close();
            return bytes;
        public ByteMe()
              //System.out.println("in constructor");
    }(end ByteMe.java)
    (begin ByteMe.cpp)
              Signature obtained with command:
                   "C:\Program Files\Java\jdk1.5.0_15\bin\javap.exe" -s -p ByteMe
                   Compiled from "ByteMe.java"
                   public class ByteMe extends java.lang.Object{
                   public long getFilezize(java.lang.String)   throws java.io.IOException;
                     Signature: (Ljava/lang/String;)J
                   public byte[] getBytesFromFile(java.lang.String)   throws java.io.IOException;
                     Signature: (Ljava/lang/String;)[B
                   public ByteMe();
                     Signature: ()V
         Compiled VC++ 2005 Express, run on Vista
    #include <stdlib.h>
    #include <string.h>
    #include <jni.h>
    // file operations
    #include <fstream>
    int main( int argc, char *argv[] )
         JNIEnv *env;
         JavaVM *jvm;
         JavaVMInitArgs vm_args;
         JavaVMOption options[5];
         jint res;
         jclass cls;
         jmethodID mid;
         jmethodID sizeid;
         jstring jstr;
         jobject obj_print;
         jlong filesize;
         options[0].optionString = "-Xms4M";
         options[1].optionString = "-Xmx64M";
         options[2].optionString = "-Xss512K";
         options[3].optionString = "-Xoss400K";
         options[4].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
         vm_args.nOptions = 5;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         // Create the Java VM
         res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         if (res < 0)
              printf("Can't create Java VM");
              goto destroy;
         cls = env->FindClass("ByteMe");
         if (cls == 0)
              printf("Can't find ByteMe class");
              goto destroy;
         jmethodID id_construct = env->GetMethodID(cls,"<init>","()V");
         printf("%s\n",id_construct);
         jstr = env->NewStringUTF(" from C++!\n");
         if (jstr == 0)
              // Normally not useful
              printf("Out of memory (could not instantiate new string jstr)\n");
              goto destroy;
         obj_print = env->NewObject(cls,id_construct);
         //BEGIN BLOCK to get file size
         sizeid = env->GetMethodID(cls, "getFilezize", "(Ljava/lang/String;)J");
         if (sizeid == 0)
              printf("Can't find ByteMe.getFilezize\n");
              goto destroy;
         else
              printf("got here\n");
              filesize =(jlong) env->CallObjectMethod(obj_print,sizeid,jstr);
              printf("got filesize\n");
         // END BLOCK to get file size
         // BEGIN BLOCK to write file
         mid = env->GetMethodID(cls, "getBytesFromFile", "(Ljava/lang/String;)[B");
         if (mid == 0)
              printf("Can't find ByteMe.getBytesFromFile\n");
              goto destroy;
         else
              jbyteArray ret =(jbyteArray) env->CallObjectMethod(obj_print,mid,jstr);
              // Access the bytes:
              jbyte *retdata = env->GetByteArrayElements(ret, NULL);
              // write the file
              std::ofstream out("data.bmp", std::ios::binary);
              //out.write ((const char *)retdata, 921654);
              out.write ((const char *)retdata, (long)filesize);
         // END BLOCK to write file
         destroy:
             if (env->ExceptionOccurred())
                env->ExceptionDescribe();
        jvm->DestroyJavaVM();
    }(end ByteMe.cpp)

  • Binary file text file

    I need to read binary file (actualy text file was saved in binary format) and convert to text file. After finished program, I must store this text file to binary format for use in next time. Anyone have any idea or suggestion will be usefull and great thanks

    I need to read binary file (actualy text file was
    saved in binary format) and convert to text file.
    After finished program, I must store this text file
    to binary format for use in next time. Anyone have
    any idea or suggestion will be usefull and great
    thanksLook, every bit of text stored in a computer is stored in a binary format. The familiar ASCII bytes format is merely the most common of them. But, to the filing system, it's just another binary file.
    Java deals with many different ways of encoding text as binary. Mostly these are called "character encodings". The second most common one is UTF-8 which stores non-latin chacters as multi byte sequences. Also java can store and retrieve text from mixed file formats in which only part of the data is text.
    You'll get nowhere unless you can find out what binary format the text is stored in.
    In general java handles binary using Stream objects and text using Reader and Writer objects.

  • Read binary file in as string to perform RegEx

    I have a python script that I use to gather data from a particular data file. I want to convert the script into a java application so I can add a gui and make it more distributable. I am particularly struggling on how to read the binary file into java and convert it to a string for the regex searching.
    import re
    dat = 'c:/projects/test.dat'
    all_the_data = open(dat,'rb').read()
    pattern = 'title="(.*?)".*?value="(.*?)"'
    rx = re.compile(pattern, re.IGNORECASE|re.MULTILINE|re.DOTALL)
    result = rx.findall(all_the_data)
    for title, value in result:
        print "%-25s: %s" % (title, value)

    Hi infraray.
    Check my post out: Cyclomatic Complexity Using Regex .
    This will help.
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    1) static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    2) protected String txtFileName;
    3) System.out.println("Enter file name to be read: " );
    4) txtFileName = new String(keyboard.readLine());
    5) reader = new BufferedReader(new FileReader(txtFileName));
    // Your Pattern |
    V
    6) Pattern pattern = Pattern.compile("if|for|while|case|switch",Pattern.MULTILINE);
    7) Matcher m = pattern.matcher(txtFileName);
    8) boolean b = m.matches(); // return true if match found !
    9) String line = null;
    10) while((line = reader.readLine()) !=null)
    m.reset(line);
    if(m.find())
    // Change line below to suit your need
    System.out.println("Your message " + " found " + " start of line: " + m.start() + " ends at line: " +m.end());
    reader.close(); // close buffered reader!
    Hope this gives you some direction.

  • Reading little endian binary files

    Hi,
    Recently I tried to read from a little endian binary files. Here is the code:
    FileInputStream file_input = new FileInputStream (file);
    DataInputStream data_in = new DataInputStream (file_input );
    while (true) {
    try {
    short i_data = data_in.readShort ();
    catch (EOFException eof) {
    System.out.println ("End of File");
    break;
    System.out.println ( i_data );
    But I am getting wrong values (big-endian). I will be pleased if anyone can help me in this respect.

    Hi,
    Finally, I can do it easily with reading little endian binary files in java. Here is the code:
    FileInputStream file_input = new FileInputStream (file);
    DataInputStream data_in = new DataInputStream (file_input );
    while (true) {
    try {
    int low = data_in.readByte() & 0xff;
    int high = data_in.readByte() & 0xff;
    short i_data = (short) (high << 8 | low) ;
    catch (EOFException eof) {
    System.out.println ("End of File");
    break;
    System.out.println ( i_data );
    }

  • Getting problem while editing a binary file

    Hi All,
    I am trying to edit a binary file using Java.The file contain a string that I have to replace with some other string.For exanple let us assume following is the content of the file -
    õgëÓÌ©™ÿÿ ABC õgëÓÌ©™ÿÿ
    Here, I have to replace this ABC(a string) with some other string.Now,if the replace string length is more than 3(the length of exiting string) then, the binary file is generating some blank space at the end.
    My Code::
    //Here I am trying to insert "Hello" in place of "ABC".
    FileInputStream fis = null;
    fis = new FileInputStream(aFile);
    FileOutputStream to = new FileOutputStream(aF);
    byte[] aTes=new byte[1024];
    String str="Hello";
    aTes=str.getBytes();
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
    to.write(buffer, 0, 5);
    to.write(aTes);
    to.write(buffer, 5, bytesRead);
    Plesae guide me to solve this problem.
    Regards,
    Soumitra

    Okay. So was that code you posted supposed to be a failed answer to the question, and you need help with fixing it? Because to me it just looks like code which copies a file, with random modifications. It doesn't look for ABC in any way, it uses the magic number "5" for no apparent reason, and the other modifications are buggy too. So clarification of what the code is supposed to be would be helpful.

  • How to create Binary File

    Hi all,
    Please can anybody tell how to crate a Binary file in Java? because I have to convert a MP3 file into a binary file and store it into a Database as binary value.
    Thanks in advance
    -Nelson

    jwenting wrote:
    paulcw wrote:
    An MP3 file is already in a binary format.
    Binary basically just means "not text".strictly speaking a text file is also binary, in that it's in the end just a stream of bits interpreted in a specific way :)It's like saying "animal" as opposed to "human". Strictly speaking, humans are a subset of animals, but when people say "animal" they usually mean the set of animals minus the set of humans.

  • Store a uploaded file of type binary into a java.sql.Blob

    Hi all,
    I try a File-Upload and store the file in a  java.sql.Blob of a MaxDB.
    My Problem is, that I'm not able to import a Model-Attribute of data type byte[]. Further I don't no how to convert the uploaded value attribute of data type binary, in a java.sql.Blob.
    Regards,
    Silvia Hofmann

    http://www.excelsior-usa.com/jet.html
    http://www.ej-technologies.com/products/exe4j/overview.html
    http://jsmooth.sourceforge.net/
    Distributing your Application as an executable JAR file
    Google is your friend.

  • Import binary file in cvs repository through java cvs import command

    hi ,
    I am using netbean api for cvs command.I am having the same problem that i am not able to open binary file after importing in cvs repository.
    I want to import a directory which contain both text and binary file.
    can you please hel me out to how to import a directory which contain binary files.
    MY CODES
    ImportCommand command = new ImportCommand();
    command.setModule(module);
    command.setLogMessage(comment);
    command.setReleaseTag(releaseTag);
    command.setImportDirectory(path);
    client.setLocalPath(path);
    command.setVendorTag(vendorTag);
    Regards
    ruchira

    Please don't cross post
    http://forum.java.sun.com/thread.jspa?messageID=9455793

  • Binary file, java

    Binary file, java, please fix these to just work when we try to download anything, Firefox 5 for example. I like to use Firefox desktop and mobile. It happens every time I download binary file, java script.

    FileInputStream

  • Binary File reading in Java

    can i read binary format file with java? if so, can you please suggest which class i should be looking into?
    Thanks

    FileInputStream

Maybe you are looking for

  • How to hook up a Linksys WRT54G to Motorola NVG589. PLEASE HELP!

    Hello,  I have recently switched over to AT&T Uverse and I am loving it. One thing I miss is having extra ethernet ports to plug in my desktop computer and my Xbox 360. When the Uverse technician came in, he installed a Motorola NVG589 modem that als

  • Desktop & Document Restriction

    I have a domain server 2012 R2 I want a policy from GPO that user can't save file in desktop & Document.

  • Tns time out windows client , server on linux oracle 11g R1

    I have Windows 7 as the host machine and Oracle 11g R1 client installed on it. I installed VMWare V5.5 (downloaded from oracle site) and then installed Linux on it as guest OS. I have Oracle database 11g R1 intalled on Linux. I can ping the Linux ser

  • IOS IPS 3845 router

    The IOS IPS keeps failing. For some reason it sends the alerts to MARS and then all of a sudden the IPS is disabled on the interface. This config. was down through SDM.

  • Please suggest the best approach

    Hi , e have a requirement of integrating two webcenter/ADF 11.1.1.6 applications .Thease two applications are running on two different environments. Please suggest us the best approach. As per the documentation we have the options: 1) 2nd App consume