GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Read, translate to hex, write? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Read, translate to hex, write?" Watch "Read, translate to hex, write?" New topic
Author

Read, translate to hex, write?

Will Carpenter
Greenhorn

Joined: Mar 17, 2004
Posts: 26
I'm trying to read a character from an input file, translate it to hex and write the hex characters to an output file. Any suggestions?

What I have so far
import java.io.*;
class TrivialApplication
{ public static void main(String args[])
{
int i;
String inf = "p3in.txt";
String ouf = "pout.txt";
FileInputStream fin;
FileOutputStream fou;

try
{ fin = new FileInputStream(inf);//set up input file
}
catch(FileNotFoundException fnf)
{ System.out.println(inf);
return;
}

try
{ fou = new FileOutputStream(ouf);//set up output file
}
catch(FileNotFoundException fnf)
{ System.out.println(fnf);
return;
}

try
{
do
{
i = fin.read(); //read a char in; write a char out
if(i != -1)
{
???;

fou.write(?);
}
}
while(i != -1);
}
catch(IOException ioe)
{ System.out.println("File error");
}
fin.close();
fou.close();
}
}
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
You have the character as an int. Look at the Integer class and see if there isn't a method just made for you.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Will Carpenter
Greenhorn

Joined: Mar 17, 2004
Posts: 26
Thanks, Stan; but I tried
String s = Integer.toHexString(i);
already, but when I tried
fou.write(s);
that didn't work, because write() won't take a string as an arg;
is there a method that returns a hex as anything other than a String?
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Check out the methods in java.io.PrintWriter


Mike Gershman
SCJP 1.4, SCWCD in process
Will Carpenter
Greenhorn

Joined: Mar 17, 2004
Posts: 26
Thanks Mike!
I changed all of my FileOutputStreams to FileWriters (and FileInputStreams to FileReaders) and that gave me access to a write() method that writes Strings!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Read, translate to hex, write?