Can someone help me with read/write using Java?

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
daskino12Asked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
Works fine for me. Called like

System.out.println(openBinaryFile("somefile.txt"));
0
 
yongsingCommented:
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
 
daskino12Author Commented:
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
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
daskino12Author Commented:
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
 
yongsingCommented:
>> 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
 
daskino12Author Commented:
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
 
yongsingCommented:
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
 
yongsingCommented:
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
 
CEHJCommented:
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
 
daskino12Author Commented:
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
 
daskino12Author Commented:
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
 
CEHJCommented:
>>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
 
daskino12Author Commented:
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
 
CEHJCommented:
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
 
daskino12Author Commented:
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
 
daskino12Author Commented:
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
 
daskino12Author Commented:
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
 
CEHJCommented:
OK. Just do

String s = openBinaryFile("somefile.txt");
0
 
daskino12Author Commented:
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
 
daskino12Author Commented:
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
 
CEHJCommented:
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
 
daskino12Author Commented:
Hello,

I am sorry..what do you mean?

So, it's hard to write it then?

THanks
0
 
CEHJCommented:
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
 
daskino12Author Commented:
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
 
daskino12Author Commented:
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
 
daskino12Author Commented:
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
All Courses

From novice to tech pro — start learning today.