简体   繁体   English

将EBCDIC转换为ASCII的Java程序

[英]java program to convert EBCDIC to ASCII

I wrote a simple java program to convert EBCDIC to ASCII. 我编写了一个简单的Java程序,将EBCDIC转换为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 步骤1:产生ebcdic.txt

Now, wrote following java program to convert ebcdic to ascii 现在,编写以下java程序将ebcdic转换为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. 请让我知道我在做什么错以及如何解决。

By calling rdr.read() you read one byte. 通过调用rdr.read()可以读取一个字节。 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. 如果将每个numericChar作为一个字节写入一个文件,则两个文件看起来相同。 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 . System.out.println()System.out.print()之间的区别在于, println将在通过附加换行符\\n打印值之后开始新的一行。

您需要像这样对char强制转换line (这是表示单个字符的int的可怕名称)。

System.out.println((char) line);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM