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.

Similar Messages

  • Read in a file and convert into Binary

    Hi there, i am new to java so plz give me a hand on this problem.
    I am suppose to read in a file(with whole bunch of different records), and what i need to do is convert the file into binary.....how do i do that??
    the original Q asked:
    Create a java program that will read the products file and write the products data into a java binary file. Adhere to good data typing conventions. That means, if a column in the input file is of type integer, then the data in that column should also be written to the output file in integer format. Same thing for String...
    Here is the code i have so far
    import java.io.*;
    class FileIO {
    /* Main method */
    public static void main(String[] args) throws IOException {
         FileReader file1 = new FileReader("test.txt");
         BufferedReader fileInput = new BufferedReader(file1);
         FileWriter file2 = new FileWriter("test1.txt");
         PrintWriter fileOutput = new PrintWriter(file2);
         String text;
         text = fileInput.readLine();
         //toBinaryString(text); <---i think there is something to do with the tobinary string but i am not sure
              System.out.println(text);
              fileOutput.println(text);
         // Close file
         fileInput.close();
         fileOutput.close();
    E-mail me directly if it's possible, thanks a lot~!!!!!

    Maybe not the answer the teacher is looking for, but I'd be highly tempted to point out that the file, regardless of what's in it, is already binary. Even if it's a text file, what do you think the characters are defined as? Bytes.

  • Read linux lastlog file and convert to a String

    Hi
    I am trying to read the data from the lastlog file in Linux. I think this is a binary file encoded in ASCII. How would I go about reading this file and converting the binary data into a String and then displaying the data? Each bit of data is separated by a new line to distinguish between the different values.
    Many Thanks
    Sambo

    "Binary file encoded in ASCII"? Well, you'd have to find out what encoding was used and then reverse is.
    As for reading files in general, check here:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • Read an excel file and convert to a 1-D array of long, 32-bit integer?

    My vi right now reads an column of numbers as a 1-D array, but I need to input the numbers manually, and for what I'm trying to do, there could be anywhere between 100 to 500 numbers to input. I want the vi to be able to read the excel file and use that column of numbers for the rest, which the data type is long (32-bit integer).
    I have an example vi that is able to get excel values, but the output data type is double (64-bit real).
    I need to either be able to convert double(64-bit real) data to long (32-bit integer), or find another way to get the values from the excel file.

    Just to expand on what GerdW is saying.  There are many programs that hold exclusive access to a file.  So if a file is opened in Excel, the LabVIEW cannot access the file.
    What is the exact error code?  Different error codes will point to different issues.
    Make sure the csv file is exactly where you think it is and LabVIEW is pointing to the right place.  (I'm just going through stupid things I have done)
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Read a txt file and save the value to array --PowerShell

    Hi Scriping guy.
      Now i have a server name list , what i want to do was to build a array based on the txt file. The txt file looks like below.
    servername1,servername2,servername3,............servernameN
      Can anyone help me ,thanks soooo much.

    Try this
    $servers = import-csv Serverlist.txt
    foreach ($server in $servers)
    #Do Something
    Regards Chen V [MCTS SharePoint 2010]

  • I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?

    I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
    Attachments:
    try2.txt ‏2 KB
    read_array.vi ‏21 KB

    The problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
    Here are some of your choices to fix your problem.
    1. Change the source file to a tab delimited file. Your VI will then run as is.
    2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
    3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
    Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
    Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does.

  • How to read flat file and convert to xml throught OSB

    Hi ,
    Can somebody help how to read flat file and convert to xml in OSB.
    appreciate ur help.
    Thanks & Regards ,
    Siva K Divi

    if you're using the oepe with osb plugin (will be installed when you install the osb locally) and then in your osb project > rightmouseclick > new > MFL.
    that's it
    maybe you're trying to create it within an oepe installation which doesnt have the osb plugin ?

  • Read a CSV file and dynamically generate the insert

    I have a requirement where there are multiple csv's which needs to be exported to a sql table. So far, I am able to read the csv file and generate the insert statement dynamically for selected columns however, the insert statement when passed as a parameter
    to the $cmd.CommandText
    does not evaluate the values
    How to evaluate the string in powershell
    Import-Csv -Path $FileName.FullName | % {
    # Insert statement.
    $insert = "INSERT INTO $Tablename ($ReqColumns) Values ('"
    $valCols='';
    $DataCols='';
    $lists = $ReqColumns.split(",");
    foreach($l in $lists)
    $valCols= $valCols + '$($_.'+$l+')'','''
    #Generate the values statement
    $DataCols=($DataCols+$valCols+')').replace(",')","");
    $insertStr =@("INSERT INTO $Tablename ($ReqColumns) Values ('$($DataCols))")
    #The above statement generate the following insert statement
    #INSERT INTO TMP_APPLE_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )
    $cmd.CommandText = $insertStr #does not evaluate the values
    #If the same statement is passed as below then it execute successfully
    #$cmd.CommandText = "INSERT INTO TMP_APL_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )"
    #Execute Query
    $cmd.ExecuteNonQuery() | Out-Null
    jyeragi

    Hi Jyeragi,
    To convert the data to the SQL table format, please try this function out-sql:
    out-sql Powershell function - export pipeline contents to a new SQL Server table
    If I have any misunderstanding, please let me know.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna
    TechNet Community Support

  • How can i read the text files and buffer the data in Vector?

    hi. I have been running into this problem for days, but with no luck and losing right direction.
    The problem is : I am trying to read a text file and buffer the data into a
    Queue for each user.
    the sample text file is as below:( 1st column is timestamp, 2nd is user_id, 3rd is packet_id, 4th is packet_seqno, 5th is packet_size)
    0 1 1 1 512
    1 2 1 2 512
    2 3 1 3 512
    3 4 1 4 512
    4 5 1 5 512
    5 6 1 6 512
    6 7 1 7 512
    7 8 1 8 512
    8 9 1 9 512
    9 10 1 10 512
    10 1 2 11 512
    11 2 2 12 512
    12 3 2 13 512
    13 4 2 14 512
    14 5 2 15 512
    15 6 2 16 512
    16 7 2 17 512
    17 8 2 18 512
    18 9 2 19 512
    19 10 2 20 512
    20 1 3 21 512
    21 2 3 22 512
    22 3 3 23 512
    23 4 3 24 512
    24 5 3 25 512
    25 6 3 26 512
    26 7 3 27 512
    27 8 3 28 512
    28 9 3 29 512
    29 10 3 30 512
    30 1 4 31 512
    31 2 4 32 512
    32 3 4 33 512
    33 4 4 34 512
    34 5 4 35 512
    35 6 4 36 512
    36 7 4 37 512
    37 8 4 38 512
    38 9 4 39 512
    39 10 4 40 512
    40 1 5 41 512
    41 2 5 42 512
    42 3 5 43 512
    43 4 5 44 512
    44 5 5 45 512
    45 6 5 46 512
    46 7 5 47 512
    47 8 5 48 512
    48 9 5 49 512
    49 10 5 50 512
    50 1 6 51 512
    51 2 6 52 512
    52 3 6 53 512
    53 4 6 54 512
    54 5 6 55 512
    55 6 6 56 512
    56 7 6 57 512
    57 8 6 58 512
    58 9 6 59 512
    59 10 6 60 512
    60 1 7 61 512
    61 2 7 62 512
    62 3 7 63 512
    63 4 7 64 512
    64 5 7 65 512
    65 6 7 66 512
    66 7 7 67 512
    67 8 7 68 512
    68 9 7 69 512
    69 10 7 70 512
    70 1 8 71 512
    71 2 8 72 512
    What I wanna do is to read all the data above and buffer them in a queue for each user( there are only 10 users in total).
    I already created a class called Class packet:
    public class packet {
        private int timestamp;
        private int user_id;
        private int packet_id;
        private int packet_seqno;
        private int packet_size;
        /** Creates a new instance of packet */
        public packet(int timestamp,int user_id, int packet_id,int packet_seqno, int packet_size)
            this.timestamp = timestamp;
            this.user_id=user_id;
            this.packet_id=packet_id;
            this.packet_seqno=packet_seqno;
            this.packet_size=packet_size;
    }then I wanna to create another Class called Class user which I can create a queue for each user (10 users in total) to store type packet information. the queue for each user will be in the order by timestamp.
    any idea and sample code will be appreciated.

    Doesn't sound too hard to me. Your class User (the convention says to capitalize class names) will have an ArrayList or Vector in it to represent the queue, and a method to store a Packet object into the List. An array or ArrayList or Vector will hold the 10 user objects. You will find the right user object from packet.user_id and call the method.
    Please try to write some code yourself. You won't learn anything from having someone else write it for you. Look at sample code using ArrayList and Vector, there's plenty out there. Post in the forum again if your code turns out not to behave.

  • Reading A xml file and sending that XML Data as input  to a Service

    Hi All,
    I have a requirement to read(I am using File adapter to read) a xml file and map the data in that xml to a service(schema) input variable.
    Example of  xml file that I have to read and the content of that xml file like below:
      <StudentList>
        <student>
           <Name> ravi</Name>
           <branch>EEE</branch>
          <fathername> raghu</fathername>
        </student>
      <student>
           <Name> raju</Name>
           <branch>ECE</branch>
          <fathername> ravi</fathername>
        </student>
    <StudentList>
    I have to pass the data(ravi,EEE,raghu etc) to a service input varible. That invoked Service input variable(schema) contains the schema similar to above schema.
    My flow is like below:
      ReadFile file adapter -------------------> BPEL process -----> Target Service.I am using transform activity in BPEL process to map the data from xml file to Service.
    I am using above xml file as sample in Native Data format(to create XSD schema file).
    After I built the process,I checked file adapter polls the data and receive the file(I am getting View xml document in EM console flow).
    But transform activity does not have anything and it is not mapping the data.I am getting blank data in the transform activity with only element names like below
    ---------------------------------------------------------------------------EM console Audit trail (I am giving this because u can clearly understand what is happening-----------------------------------------------------
       -ReceiveFile
            -some datedetails      received file
              View XML document  (This xml contains data and structure like above  xml )
        - transformData:
            <payload>
              <InvokeService_inputvariable>
                  <part name="body">
                     <StudentList>
                         <student>
                           <name/>
                            <branch/>
                            <fathername/>
                         </student>
                   </StudentList>
              </part>
             </InvokeService_inputvariable>
    'Why I am getting like this".Is there any problem with native data format configuration.?
    Please help me out regarding this issue as I am running out my time.

    Hi syam,
    Thank you very much for your replies so far so that I have some progrees in my task.
    As you told I could have put default directory in composite.xml,but what happenes is the everyday new final subdirectory gets created  in the 'soafolder' folder.What I mean is in  the c:/soafolder/1234_xmlfiles folder, the '1234_xmlfiles' is not manually created one.It is created automatically by executing some jar.
    Basically we can't know the sub folder name until it is created by jar with its own logic. whereas main folder is same(soafolder) ever.
    I will give you example with our folder name so that it would be more convenient for us to understand.
    1) yesterday's  the folder structure :  'c:/soafolder/130731_LS' .The  '130731_LS' folder is created automatically by executing some jar file(it has its own logic to control and create the subdirectories which is not in our control).
    2) Today's folder structure :  'c:/soafolder/130804_LS. The folder is created automatically(everytime the number part(130731,130804).I think that number is indicating 2013 july 31 st like that.I have to enquire about this)is changing) at a particular time and xml files will be loaded in the folder.
    Our challenge : It is not that we can put the default or further path in composite.xml and poll the file adapter.Not everytime we have to change the path in composite.xml.The process should know the folder path (I don't know whether it is possible or not.) and  everyday and file adapter poll the files in that created subfolders.
    I hope you can understand my requirement .Please help me out in this regard.

  • Read a property file and store it in a hashmap

    Hi,
    I have tried to read a property file and store it in a hashmap. The property-names should be stored in keys and the property-values (after = symbol) in values of the hashmap. any ideas? Is it possible to do this?

    mandy2001ir wrote:
    yes, but I need the hashmap for another reason. Actually I'm trying to use the properties file to have a dynamic hachmap. I don't want to change the code anytime I want to put a value in the hashmap. therefor I write the "keys" and "values" in a property file and change the property file. That's the reasn why we have property files, isn't it?What's a "dynamic hashmap"? There's no other kind! Whenever someone starts bandying around the word "dynamic" in contexts like this, it usually means there's a simple solution to their problem, that they haven't yet considered, or mistakenly don't believe is applicable to them, because of this "unique" need for something "dynamic". Trust me, you just need to load the file using a Properties object, and you're done. Properties extends Hashtable, which is virtually the same thing as a HashMap. Properties does exactly what you want it to. it's the very reason the class exists
    Have you even looked at the javadoc for java.util.Properties yet? I'm betting not, because if you had, you'd know exactly what I meant. And since you haven't, I'm at a bit of a loss as to how you can so easily dismiss the class as useless, despite existing to do exactly what you need

  • Read a csv file and read the fiscal yr in the 4th pos?

    Hello ABAP Experts,
    how to write a code for read a csv file and read the fiscal year in the 4th position.
    any suggestions or code highly appreciated.
    Thanks,
    BWer

    Hi Bwer,
    Declare table itab with the required fields...
    Use GUI UPLOAD to get the contents of the file (say abc.csv) in case if the file is on the presentation server...
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename                        = 'c:\abc.csv'
       FILETYPE                        = 'ASC'
        WRITE_FIELD_SEPARATOR           = 'X'
      tables
        data_tab                        = itab
    EXCEPTIONS
       FILE_WRITE_ERROR                = 1
       NO_BATCH                        = 2
       OTHERS                          = 22
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
             WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    Use OPEN DATASET in case if the file is on the application server..
    After that USE SPLIT command at comma to get the contents of the 4th field...
    Regards,
    Tanveer.
    <b>Please mark helpful answers</b>

  • Reading a CSV file and producing an array of objects

    Hi everybody,
    I am writing an application which will read a cvs file and produce an array of objects.
    Can any body help me to solve this problem?
    Thanks
    Finny

    Hello,
    Have you tried this link?
    http://ostermiller.org/utils/CSV.html

  • Read multiple text files and sort them

    I am trying to read multiple text files and store the data from the file in vector.
    but for days. I am with no luck. anyone can help me out with it? any idea of how to sort them will be appreciated.
    Below is part of the code I implemented.
    public class packet {
        private int timestamp;
        private int user_id;
        private int packet_id;
        private int packet_seqno;
        private int packet_size;
        public packet(int timestamp0,int user_id0, int packet_id0,int packet_seqno0, int packet_size0)
            timestamp = timestamp0;
            user_id=user_id0;
            packet_id=packet_id0;
            packet_seqno=packet_seqno0;
            packet_size=packet_size0;
        public void setTime(int atimestamp)
            this.timestamp=atimestamp;
        public void setUserid(int auserid)
            this.user_id=auserid;
        public void setPacketid(int apacketid)
            this.packet_id=apacketid;
        public void setPacketseqno(int apacketseqno)
            this.packet_seqno=apacketseqno;
        public void setPacketsize(int apacketsize)
            this.packet_size=apacketsize;
        public String toString()
            return timestamp+"\t"+user_id+"\t"+packet_id+"\t"+packet_seqno+"\t"+packet_size+"\t";
    }Here is the data from part of the text files. ( the first column is timestamp, second is userid, third is packetid.....)
    0 1 1 1 512
    1 2 1 2 512
    2 3 1 3 512
    3 4 1 4 512
    4 5 1 5 512
    5 6 1 6 512
    6 7 1 7 512
    7 8 1 8 512
    8 9 1 9 512
    9 10 1 10 512
    10 1 2 11 512
    11 2 2 12 512
    12 3 2 13 512
    13 4 2 14 512
    14 5 2 15 512
    15 6 2 16 512
    16 7 2 17 512

    Here's a standard idiom for object-list-sorting:
    /* cnleafdata.txt *********************************************
    0 1 1 1 512
    1 2 1 2 512
    2 3 1 3 512
    3 4 1 4 512
    4 5 1 5 512
    5 6 1 6 512
    6 7 1 7 512
    7 8 1 8 512
    8 9 1 9 512
    9 10 1 10 512
    10 1 2 11 512
    11 2 2 12 512
    12 3 2 13 512
    13 4 2 14 512
    14 5 2 15 512
    15 6 2 16 512
    16 7 2 17 512
    import java.util.*;
    import java.io.*;
    public class Packet implements Comparable<Packet>{
      private int timeStamp;
      private int userId;
      private int packetId;
      private int packetSeqno;
      private int packetSize;
      public Packet(int timeStamp0, int userId0, int packetId0,
       int packetSeqno0, int packetSize0) {
        timeStamp = timeStamp0;
        userId = userId0;
        packetId = packetId0;
        packetSeqno = packetSeqno0;
        packetSize = packetSize0;
      public Packet(String timeStamp0, String userId0, String packetId0,
       String packetSeqno0, String packetSize0) {
        this(Integer.parseInt(timeStamp0), Integer.parseInt(userId0),
         Integer.parseInt(packetId0), Integer.parseInt(packetSeqno0),
         Integer.parseInt(packetSize0));
      public Packet(String[] a){
        this(a[0], a[1], a[2], a[3], a[4]);
      public void setTime(int aTimeStamp){
        timeStamp = aTimeStamp;
      public void setUserId(int aUserId){
        userId = aUserId;
      public void setPacketId(int aPacketId){
        packetId = aPacketId;
      public void setPacketSeqno(int aPacketSeqno){
        packetSeqno = aPacketSeqno;
      public void setPacketSize(int aPacketSize){
        packetSize = aPacketSize;
      public int getUserId(){
        return userId;
      public String toString(){
        return String.format
    ("%2d %2d %2d %2d %4d", timeStamp, userId, packetId, packetSeqno, packetSize);
      public int compareTo(Packet otherPacket){
        return userId - otherPacket.getUserId();
      /* main for test */
      public static void main(String[] args){
        String line;
        ArrayList<Packet> alp;
        alp = new ArrayList<Packet>();
        try{
          BufferedReader br = new BufferedReader(new FileReader("cnleafdata.txt"));
          while ((line = br.readLine()) != null){
            // if (! recordValid(line)){
            //   continue;
            String[] ar = line.split("\\s");
            alp.add(new Packet(ar));
        catch (Exception e){
          e.printStackTrace();
        System.out.println("[original]");
        for (Packet p : alp){
          System.out.println(p);
        System.out.println();
        Collections.sort(alp);
        System.out.println("[sorted by user ID]");
        for (Packet p : alp){
          System.out.println(p);
    }

  • 1.is it possible to read a .xls file and load it into an oracle table

    1.is it possible to read a .xls file and load it into an oracle table, using oracle database or oracle forms i.e. either utl_file, or text_io, or any other oracle tool.
    As far as I know we need a csv file or a txt ( tab delimited) file ?
    2.Are there any windows tools for the same

    Hi,
    If you want to use the DDE package to read the XLS file then yes, you will neeed to know the number of rows and columns in the input file.
    i.e. How will you know :
    1) How many columns are there in the input file.
    If I have a XLS file with the following data :
    R1C1 R1C2 R1C3 R1C4 R1C5 R1C6 R1C7
    xxx xx x
    Where R represents row and C represents column, then how will you know the each row has 7 columns. If you know the answer upfront, then it's not a issue.
    Using the DDE apprach, you will have to specify the RowNum and the ColumnNo of each idividual cells to read/write data from xls sheet.
    Look at the syntax in my ealier post.
    using the other approch (i.e. comma delimited text file - CSV file) , you need not know the number of columns as you can loop thru the input record till the last column is read.
    All you have to do is to look for the 'n' occurances of the field delimiter say ',', do a substr from the current position to the point where the ',' was found.
    This process is to be repeated in a loop till all columns are read.
    The TEXT_IO package can trap for EOF (End Of File).
    Hope I made myself clear.
    -- Shailender Mehta --

Maybe you are looking for

  • OADB_Creation of a new derived chart of depreciation_Message  AC166

    Hello, I try to create a new derived  depreciation area. This one contains an another derived  depreciation area in its formula. No postings have required in this new depreciation area When I try to enter, the following message displays: Message  AC1

  • Abstract class - access to parent

    Hi: I would like to do the following, but I don´t know how (neither if its possible): Access from an abstract class a method of its implementer class. public class ContainerClass () implements AbstractClass{ public void AbstractMethod(){ super().Meth

  • A few small questions

    I like the horizontal blur title in the filmstrip category of the titles browser, but it is fixed across the middle of the screen - can I adjust it to be at the bottom of the screen instead ? Also, can I insert my own overlay from a graphic that I ha

  • B NOIR NEED YOUR EXPERTISE!

    Upgraded from 4.9 to 5.0 and now the serato needs me to re-install each song into crates AGAIN. (They're all pink) This took weeks to do the first time in 4.9. Is there any way around this? Can I just go back to 4.9 with out any problems? You seem to

  • Adobe InDesign Installation Error

    I keep having errors when installing. Please help, I'm installing InDesign CS6 trial.