2

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.

user2942227
  • 1,023
  • 6
  • 19
  • 26

2 Answers2

4

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.

MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44
1

You need to cast line (which is a terrible name for an int representing a single character) to char, like this.

System.out.println((char) line);
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • It worked, thanks. But it printed single character in 1 line like s \n a \n m\n p\n\nl\ne\n1\n2\n1\n2...How do I print it line by line as in input? – user2942227 Aug 18 '14 at 17:36
  • @user2942227 Do you understand what `println` does? – ajb Aug 18 '14 at 17:38