Solved

Can someone help me with read/write using Java?

Posted on 2003-10-22
26
768 Views
Last Modified: 2010-03-31
Hello,

I was wondering if anyone knows how to open a input file (public static String openBinaryFile( String filename) )and then return a string holding he ontntsof te nput file, converted to hexadecimal.

Thanks
0
Comment
Question by:daskino12
  • 15
  • 7
  • 4
26 Comments
 
LVL 9

Expert Comment

by:yongsing
ID: 9604454
See method below. I have declared a "throws IOException" in case there is an error while reading the file.

public static String openBinaryFile( String filename) throws IOException {
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
      int byteRead;
      StringBuffer hexContent = new StringBuffer();
      while ((byteRead = in.read()) != -1) {
          String hex = Integer.toHexString(byteRead).toUpperCase();
          hexContent.append(hex);
          if (hex.length() < 2) {
              hexContent.append("0");
          }
      }
      in.close();
      return hexContent.toString();
}
0
 

Author Comment

by:daskino12
ID: 9604472
Hello,

Thank you very much for helping.  I just have a few questions:

1)I was to o ue Integer.toString(((byte)ch& 0xff) + 0x100, 16).substring(1.  Is it any different fr uor hex coversion?

2)  the output is like the following:

Input:

race carrot or race car
I prefer pi
kayak

Input(after Open as binary:

72 61 63 65 20 63 61 72 72 6f 74 20 6f 72 20
....

Thanks


0
 

Author Comment

by:daskino12
ID: 9604500
Hello,

I am sorry...it's like I need 2 hexadecial characters for each byte, one space between eery two hex charactersand 15 bytes of hexadecimal characters in each line..

Thanks
0
 
LVL 9

Expert Comment

by:yongsing
ID: 9604752
>> 1)I was to o ue Integer.toString(((byte)ch& 0xff) + 0x100, 16).substring(1.  Is it any different fr uor hex coversion?

It's the same as mine.



>> I am sorry...it's like I need 2 hexadecial characters for each byte, one space between eery two hex charactersand 15
>> bytes of hexadecimal characters in each line..

Here you go:

public static String openBinaryFile( String filename) throws IOException {
     BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
     int byteRead;
     StringBuffer hexContent = new StringBuffer();
     int i = 0;
     while ((byteRead = in.read()) != -1) {
         if (++i == 16) {
             System.out.println(byteRead + " " + i);
             hexContent.append("\n");
             i = 1;
         } else if (hexContent.length() > 0) {
             hexContent.append(" ");
         }
         String hex = Integer.toHexString(byteRead).toUpperCase();
         hexContent.append(hex);
         if (hex.length() < 2) {
             hexContent.append("0");
         }
     }
     in.close();
     return hexContent.toString();
}
0
 

Author Comment

by:daskino12
ID: 9604772
Hello,

I am sorry..but for one last question (i hope)..I do not want to use system.out.println because it will print out in command prompt.  I need the function to print out in the Text Editor I create..(so it display in the text editor).  Can i just create a string and output it in the text editor?

Thanks
0
 
LVL 9

Expert Comment

by:yongsing
ID: 9604814
Sure you can. Just use my original method below:


public static String openBinaryFile( String filename) throws IOException {
     BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
     int byteRead;
     StringBuffer hexContent = new StringBuffer();
     while ((byteRead = in.read()) != -1) {
         String hex = Integer.toHexString(byteRead).toUpperCase();
         hexContent.append(hex);
         if (hex.length() < 2) {
             hexContent.append("0");
         }
     }
     in.close();
     return hexContent.toString();
}


Then you can call it and display the content in a TextArea or JTextArea:

 try {
         String content = openBinaryFile(args[0]);
         int i = 0;
         while (i < content.length()) {
             if (i > 0) {
                 if (i % 30 == 0) {
                     textArea.append("\n");
                 } else {
                     textArea.append(" ");
                 }
             }
             textArea.append(content.substring(i, i + 2));
             i += 2;
         }
} catch (IOException e) {}
0
 
LVL 9

Expert Comment

by:yongsing
ID: 9604857
Some changes:

try {
        String content = openBinaryFile("thefile.txt");
        int i = 0;
        textArea.setText("");
        while (i < content.length()) {
            if (i > 0) {
                if (i % 30 == 0) {
                    textArea.append("\n");
                } else {
                    textArea.append(" ");
                }
            }
            textArea.append(content.substring(i, i + 2));
            i += 2;
        }
} catch (IOException e) {}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9605998
Try:

  public static String openBinaryFile( String filename) throws IOException {
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int buf = -1;
      while ((buf = in.read()) != -1) {
          out.write(buf);
      }
      in.close();
      return new sun.misc.HexDumpEncoder().encode(out.toByteArray());
  }
0
 

Author Comment

by:daskino12
ID: 9607276
Hello,

Some how I can't use "throws IOException" because I would get compile errors.  Because I have defined my previous part of programming as the following:

                if( arg.equals( "Open as binary..." ) ) {
                        openDialog.show();
                        String temp = openDialog.getFile();
                               
                        if( temp != null ) {
                                filename = temp;
                                binaryFile = true;
                                cbMenuItem.setState( true );
                                setTitle( windowName + filename );
                                ta.setText( hw9.openBinaryFile( filename ) );
                        }
                }

So, whenever I use "throws IOException", i will get "unreported exception java.io.IOException; must be caught or declared to be thrown ta.setText( hw9.openBinaryFile( filename ) );"

And if I don't add "throws IOException", i will get the following error:

-unreported exception java.io.IOException; must be caught or declared to be thrown
                                ta.setText( hw9.openBinaryFile( filename ) );
-unreported exception java.io.IOException; must be caught or declared to be thrown
        while ((byteRead = in.read()) != -1) {
-unreported exception java.io.IOException; must be caught or declared to be thrown
     in.close();
-unreported exception java.io.IOException; must be caught or declared to be thrown
     in.close();

This is assumed I tried  yongsing's code:

public static String openBinaryFile( String filename) throws IOException {
     BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
     int byteRead;
     StringBuffer hexContent = new StringBuffer();
     while ((byteRead = in.read()) != -1) {
         String hex = Integer.toHexString(byteRead).toUpperCase();
         hexContent.append(hex);
         if (hex.length() < 2) {
             hexContent.append("0");
         }
     }
     in.close();
     return hexContent.toString();
}

Thanks
0
 

Author Comment

by:daskino12
ID: 9607291
Hello

I have also tried CEHJ's method but it's not properly formated and I try to stick to the conversion of  "Integer.toString(((bte)ch &0xff 0+ 0x100, 16).substring(1) because I dont understand "new sun.misc.HexDumpEncoder().encode(out.toByteArray());"

Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9608112
>>but it's not properly formated

Not sure what you mean by that.

>>because I dont understand "new sun.misc.HexDumpEncoder().encode(out.toByteArray());"

It just gives a proper hex editor output

0
 

Author Comment

by:daskino12
ID: 9608138
Hello,

I am sorry about my unclear question.  What I meant about the format is the following:

-two hexadecimal characters for each byte (example: 0A)
-one space between every two hex characters (example: 61 62)
-15 bytes of hexadecimal characters in each line

Thanks

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9608173
Here are the first few of a class file lines printed with just such a formatting using my code. Of course, things look much better in a monospaced font:


0000: CA FE BA BE 00 03 00 2D   00 29 0A 00 08 00 11 09  .......-.)......
0010: 00 12 00 13 0A 00 12 00   14 0A 00 15 00 16 0A 00  ................
0020: 12 00 17 0A 00 18 00 19   07 00 1A 07 00 1B 01 00  ................
0030: 06 3C 69 6E 69 74 3E 01   00 03 28 29 56 01 00 04  .<init>...()V...
0040: 43 6F 64 65 01 00 0F 4C   69 6E 65 4E 75 6D 62 65  Code...LineNumbe
0050: 72 54 61 62 6C 65 01 00   04 6D 61 69 6E 01 00 16  rTable...main...
0060: 28 5B 4C 6A 61 76 61 2F   6C 61 6E 67 2F 53 74 72  ([Ljava/lang/Str
0070: 69 6E 67 3B 29 56 01 00   0A 53 6F 75 72 63 65 46  ing;)V...SourceF
0080: 69 6C 65 01 00 0A 50 72   6F 70 73 2E 6A 61 76 61  ile...Props.java
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:daskino12
ID: 9608435
Hello,

I am getting the following errors.  I assume I have to use try and catch instead of "throw"  Right?  

-unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
                                                       ^
-unreported exception java.io.IOException; must be caught or declared to be thrown
      while ((buf = in.read()) != -1) {
                      ^
-unreported exception java.io.IOException; must be caught or declared to be thrown
      in.close();
0
 

Author Comment

by:daskino12
ID: 9610028
Hello,

I don't have any errors now but the function seems doesn't work properly.  Like, I opened up a txt file in my Text Editor; however, it just shows the characters but not the ASCII hexadecimal.

Do yo know why?

Here is my code:

      public static String openBinaryFile( String filename ) {
      
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int buf = -1;
      while ((buf = in.read()) != -1) {
          out.write(buf);
      }
      in.close();
      return new sun.misc.HexDumpEncoder().encode(out.toByteArray());
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 9610199
Works fine for me. Called like

System.out.println(openBinaryFile("somefile.txt"));
0
 

Author Comment

by:daskino12
ID: 9610243
Hello,

I can't use System.out.println because it will open the file in command prompt.  It does open but it won't just do the conversion..

Thanks

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9610339
OK. Just do

String s = openBinaryFile("somefile.txt");
0
 

Author Comment

by:daskino12
ID: 9610831
Hello all,

Here is my final code and it works:) Thank you all so much..however, can you please help me with this code?  I tried to save the file by using this function "void saveBinaryFile( string text, string filename)"

My working file:
       StringBuffer hexContent = new StringBuffer();
     try
     {
       BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
       int byteRead;
       int count = 0;
       while ((byteRead = in.read()) != -1) {
             count++;
         String hex = Integer.toString(((byte)byteRead & 0xff) + 0x100,16).substring(1);
         hexContent.append(hex);
      if (count < 15){
      hexContent.append(" ");
      }
      if (count == 15 ){
      hexContent.append("\n");
      count = 0;
      }
       }
       in.close();
     }

     catch(IOException e)
     {
     }
     
     return hexContent.toString();
     
     
} // openBinaryFile()


My not working file:

     public static void saveBinaryFile( String text, String filename ) {
     
          // YOUR HOMEWORK 9 CODE HERE
       try
       {
           FileOutputStream fos = new FileOutputStream(filename);
           fos.write(new java.math.BigInteger(text, 16).toByteArray());
           fos.close();
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }          
  }    

What void saveBinaryFile( string text, string filename) does is upon saving the binary file, it should convert the hex bytes back into binary and write the binary file.

Please help..

Thanks
0
 

Author Comment

by:daskino12
ID: 9610861
Hello,

I am sorry yongsing, I also wanted to give you "EXCELLENT" but I was unable to.  I am sorry because I am new here.  Thank you very much for your help, yongsing.

Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9610879
Well that last bit really relates to another question doesn't it? If you use my hex dumping code, it won't work if you take its output as input to a binary string to write back to file - but you didn't ask for that in the first place ;-)
0
 

Author Comment

by:daskino12
ID: 9610932
Hello,

I am sorry..what do you mean?

So, it's hard to write it then?

THanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9611060
saveBinaryFile works fine for me

12c499d94544f9b4bc126df256916717

was the input

and this was the dump of the file thus created:

0000: 12 C4 99 D9 45 44 F9 B4   BC 12 6D F2 56 91 67 17  ....ED....m.V.g.
0
 

Author Comment

by:daskino12
ID: 9611107
Hello,

It doesn't work for me.

      public static String openBinaryFile( String filename ) {
     
       StringBuffer hexContent = new StringBuffer();
     try
     {
       BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
       int byteRead;
       int count = 1;
       
       while ((byteRead = in.read()) != -1) {
              count++;
         String hex = Integer.toString(((byte)byteRead & 0xff) + 0x100,16).substring(1);
         hexContent.append(hex);
       if (count < 15){
       hexContent.append(" ");
       }
       if (count == 15 ){
       hexContent.append("\n");
       count = 0;
       }
       }
       in.close();
     }

     catch(IOException e)
     {
     }
     
     return hexContent.toString();

is my OpenBinary File

and the following is my SaveBinaryFile:

      public static void saveBinaryFile( String text, String filename ) {
            
       try
       {
           FileOutputStream fos = new FileOutputStream(filename);
           fos.write(new java.math.BigInteger(text, 16).toByteArray());
           fos.close();
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }            
  }      

It does'nt save anything when I use this function.

Like...it's supposed to do the following:

OpenBinaryFile:

73 45 38 29 33 45 12

Then, on my Text Editor, I edit it:

73 45 38 29 33 45 12 34

Then Save it.  It should save as to another file with the new info.

Do you know why it's not working?

Thanks  a lot
0
 

Author Comment

by:daskino12
ID: 9611128
Hello,

Like, within the TextEditor i have, the hex bytes can be edited, and upon saving the binary file, it should convert the hex bytes back into binary and write the binary file..

Thanks
0
 

Author Comment

by:daskino12
ID: 9611677
Hello,

I was wondering, do I need to read 2 characters first then convert it, then save it?
Because for this code,

     public static void saveBinaryFile( String text, String filename ) {
         
       try
       {
           FileOutputStream fos = new FileOutputStream(filename);
           fos.write(new java.math.BigInteger(text, 16).toByteArray());
           fos.close();
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }          
  }    

it seems it only convert the whole thing then save it.  Because whenver I use this function, the file I write to becomes empty.

Any suggetions?

Thanks
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now