java program to convert EBCDIC to ASCII

user2942227 picture user2942227 · Aug 18, 2014 · Viewed 10.4k times · Source

I wrote a simple java program to convert EBCDIC to ASCII. It's not working correctly. Here is what I did

Step 1: Convert ASCII file to EBCDIC using the following command :

 dd if=sampleInput.txt of=ebcdic.txt conv=ebcdic

 sampleInput.txt has following line :

input 12 12

Step 1: generated ebcdic.txt

Now, wrote following java program to convert ebcdic to ascii

public class CoboDataFilelReaderTest {

 public static void main(String[] args) throws IOException {

     int line;
     InputStreamReader rdr = new InputStreamReader(new FileInputStream("/Users/rr/Documents/workspace/EBCDIC_TO_ASCII/ebcdic.txt"), java.nio.charset.Charset.forName("ibm500"));
        while((line = rdr.read()) != -1) {
            System.out.println(line);
    }
    }
 }

It gave me wrong output, the output looks something like this :

115
97
109
112
108
101
32
49
50
32
49
50

Please let me know what I am doing wrong and how to fix it.

Answer

MinecraftShamrock picture MinecraftShamrock · Aug 18, 2014

By calling rdr.read() you read one byte. If you want to read one character of text instead of it's numeric representation, you could cast it to a character like this:

int numericChar;
InputStreamReader rdr = new InputStreamReader(new FileInputStream("/Users/rr/Documents/workspace/EBCDIC_TO_ASCII/ebcdic.txt"), java.nio.charset.Charset.forName("ibm500"));
while((numericChar = rdr.read()) != -1) {
        System.out.println((char) numericChar);
}

If you'd write each numericChar to a file as one byte, the both files would look the same. But you are writing to the console and not to a file so it represents the content as numbers instead of interpreting them as character.


If you want to output the content line by line you could do it like this:

int numericChar;
InputStreamReader rdr = new InputStreamReader(new FileInputStream("/Users/rr/Documents/workspace/EBCDIC_TO_ASCII/ebcdic.txt"), java.nio.charset.Charset.forName("ibm500"));
while((numericChar = rdr.read()) != -1) {
    System.out.print((char) numericChar);
}

This will not start a new line after each character.

The difference between System.out.println() and System.out.print() is that println will start a new line after printing the value by appending the newline character \n.