Visualizzazione dei risultati da 1 a 5 su 5
  1. #1
    Utente di HTML.it L'avatar di netarrow
    Registrato dal
    Apr 2004
    Messaggi
    1,425

    Convertire stringa da ASCII(o unicode) in EBCDIC

    Ciao a tutti,

    come da titolo, avrei la necessità di convertire delle stringhe da ASCII a EBCDIC visto che questi dati dopo dovranno essere elaborati su mainframe IBM.
    Qualcuno sa come si fa? Sennò va bene anche da unicode a ebcdic.

    grazie a tutti, ciao
    Imparare è un'esperienza, tutto il resto è solo informazione. (Albert Einstein)

  2. #2
    Utente di HTML.it L'avatar di netarrow
    Registrato dal
    Apr 2004
    Messaggi
    1,425
    Niente sono riuscito a risolvere, fiu

    codice:
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.*;
    import java.io.*;
    
    public class Test {
    
    public static void main(String[] args) {
    try {
    Charset charset = Charset.forName("IBM1047");// creo il set di caratteri rappresentante lo std EBCDIC
    
    CharsetDecoder decoder = charset.newDecoder();// creo un decodificatore da ebcdic a unicode
    CharsetEncoder encoder = charset.newEncoder();// un codificatore da unicode a ebcdic
    
    FileChannel chan;// un canale verso il file
    long size;// dimensioni file
    FileOutputStream fos = new FileOutputStream("test.txt");// stream verso il file
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("Stringa qualsiasi"));// buffer di byte contentnte
    // la stringa in ebcdic
    
    chan = fos.getChannel();// ottengo il canale dello stream
    size = chan.size();// le dimensioni(del file)
    bbuf.rewind();// mi posiziono all'inizio del buffer
    chan.write(bbuf);// lo scrivo dentro test.txt tramite il canale prima creato
    chan.close();// chiudo canale
    fos.close();// chiudo stream
    
    System.out.println("Dentro test.txt c'è la stringa in ebcdic\\n Proviamo a riconvertirla in unicode");
    bbuf.rewind();
    CharBuffer cb = decoder.decode(bbuf);
    System.out.println(cb.toString());
    if (cb.toString().equals("Stringa qualsiasi"))
    System.out.println("Ho ottenuto la stessa!!");
    
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    Imparare è un'esperienza, tutto il resto è solo informazione. (Albert Einstein)

  3. #3
    Ciao come Va?? mi sono permesso di modificare il tuo programma
    ho utilizzato una libreria che ho realizzato per manipolare i canali in maniera
    piu' semplice ed evitando molti blocchi try/catch e in piu' ho aggiunto
    una funzionalita che apre un canale per la scritturasia in accodamento che in maniera
    casuale.
    codice:
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.charset.CharacterCodingException;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    import lib.FileChannelUtilityes.IoChannel;
    import lib.FileChannelUtilityes.OutChannel;
    
    /**
     *
     * @author mau2
     */
    public class DecodeEncodeString2 {
        
        
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Charset charset = Charset.forName("IBM1047");// creo il set di caratteri rappresentante lo std EBCDIC
            
            CharsetDecoder decoder = charset.newDecoder();// creo un decodificatore da ebcdic a unicode
            CharsetEncoder encoder = charset.newEncoder();// un codificatore da unicode a ebcdic
            
            //con la seguente istruzione creiamo lo stream e apriamo il canale
            //l' argomentboolean serve per creare la directory
                    IoChannel ioChannel = new IoChannel("test.txt", false, "rw");
            
            ByteBuffer byteBuffer = null;
            try {
                // buffer di byte contenente la stringa
                byteBuffer = encoder.encode(CharBuffer.wrap("Stringa qualsiasi"));
     
            } catch (CharacterCodingException e) {
                e.printStackTrace(System.err);
            }
            
            ioChannel.write(byteBuffer);
            
            System.out.println("Dentro test.txt c'è la stringa in ebcdic\n" +
                    "Proviamo a leggerla dal file riconvertirla in unicode");
            //position del ByteBuffer impostato a zero
            byteBuffer.rewind();
            //posizioniamo il file position pointer all'inizio del file
            //per la lettura
            ioChannel.position(0);
            
            //leggiamo il file
            ioChannel.read(byteBuffer);
            
            byteBuffer.rewind();
            
            CharBuffer charBuffer = null;
            try {
                charBuffer = decoder.decode(byteBuffer);
                
            } catch (CharacterCodingException e) {
                e.printStackTrace(System.err);
            }
            
            if (charBuffer.toString().equals("Stringa qualsiasi"))
                    System.out.println("Ho ottenuto la stessa: " + charBuffer.toString());
            
            
            
        }
    }
    La libreria e' di seguito:
    codice:
    package lib.FileChannelUtilityes;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.FileLock;
    import java.nio.channels.ReadableByteChannel;
    import java.nio.channels.WritableByteChannel;
    
    
    /**
     *
     * @author mau2
     */
    /*in questa classe bisogna includere altri costruttori
     *che prevedano l'apertura dello stream con gli altri costruttori
     *overloaded della classe RandomAccessFile*/
    public class IoChannel{
        private FileChannel ioChannel;;
        private RandomAccessFile ioStream;
        private FileLock lock;
        public static final FileChannel.MapMode PRIVATE = FileChannel.MapMode.PRIVATE;
        public static final FileChannel.MapMode READ_ONLY = FileChannel.MapMode.READ_ONLY;
        public static final FileChannel.MapMode READ_WRITE = FileChannel.MapMode.READ_WRITE;
        /** Creates a new instance of IoChannel */
        
        public IoChannel(File file, boolean createDirectory, String mode) {
            if(createDirectory && !file.exists())
                createDir(file);
            try {
                ioStream = new RandomAccessFile(file, mode);
            } catch (FileNotFoundException e) {
                e.printStackTrace(System.err);
            }
            ioChannel = ioStream.getChannel();
            
        }
        
        public IoChannel(String file, boolean createDirectory, String mode) {
            File tmpFile = new File(file);
                   
            if(createDirectory && !tmpFile.exists())
                createDir(tmpFile);
            try {
                ioStream = new RandomAccessFile(tmpFile, mode);
            } catch (FileNotFoundException e) {
                e.printStackTrace(System.err);
            }
            ioChannel = ioStream.getChannel();
            
        }
        
        
        
        public int read(ByteBuffer dst) {
            int EOF = 0;
            try {
                EOF = ioChannel.read(dst);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return EOF;
        }
        public int read(ByteBuffer dst, long position){
            int EOF = 0;
            try {
                EOF = ioChannel.read(dst, position);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
            return EOF;
        }
        
        public long read(ByteBuffer[] dsts, int offset, int length){
            long EOF = 0;
            try {
                EOF = ioChannel.read(dsts, offset, length);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return EOF;
        }
        
        public long size() {
            long size = 0;
            try {
                size = ioChannel.size();
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return size;
        }
        
        public long position(){
            long seek = 0;
            try {
                seek = ioChannel.position();
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
            return seek;
        }
        
        public IoChannel position(long newPosition) {
            try {
                ioChannel.position(newPosition);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return this;
        }
        
        public boolean isOpen() {
            return ioChannel.isOpen();
        }
        
        public void close(){
            try {
                ioStream.close();
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
        }
        
        public FileChannel getOriginalChannel() {
            return ioChannel;
        }
        
        public long transferTo(long position, long count, WritableByteChannel target){
            long size = 0;
            try {
                size = ioChannel.transferTo(position, count, target);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return size;
        }
        public long transferTo(long position, long count, OutChannel target){
            long size = 0;
            try {
                size = ioChannel.transferTo(position, count, target.getOriginalChannel());
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return size;
        }
        
        public long transferTo(OutChannel target){
            
            long bytesWritten = 0;
            long byteCount = this.size();
            try {
                while(bytesWritten < byteCount){
                    bytesWritten += ioChannel.transferTo(bytesWritten, byteCount, target.getOriginalChannel());
                }
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return bytesWritten;
        }
        
        public long transferTo(WritableByteChannel target){
            
            long bytesWritten = 0;
            long byteCount = this.size();
            try {
                while(bytesWritten < byteCount){
                    bytesWritten += ioChannel.transferTo(bytesWritten, byteCount, target);
                }
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return bytesWritten;
        }
        
        
        
        public MappedByteBuffer map(FileChannel.MapMode mode, long position, long size){
            MappedByteBuffer buf = null;
            try {
                buf = ioChannel.map(mode, position, size);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return buf;
        }
        
        public MappedByteBuffer map(FileChannel.MapMode mode){
            MappedByteBuffer buf = null;
            try {
                buf = ioChannel.map(mode, 0L, this.size());
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return buf;
        }
        public FileLock tryLock(long position, long size, boolean shared){
            
            try {
                lock = ioChannel.tryLock(position, size, shared);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return lock;
        }
        public FileLock tryLock(long position, long size){
            
            try {
                lock = ioChannel.tryLock(position, size, false);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            return lock;
        }
        
        public void tryLock(){
            try {
                lock = ioChannel.tryLock();
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
        }
        
        public void releaseLock(){
            try {
                if(lock != null)
                    lock.release();
            } catch (IOException e) {
                
            }
        }
        
        public boolean isLocked(){
            if(lock == null)
                return false;
            else
                return true;
            
        }
        
        
        
        
        
        public void force(){
            try {
                ioChannel.force(true);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
        }
        
        
        public int write(ByteBuffer buf){
            
            int sizeDataWritten = 0;
            
            try{
                sizeDataWritten = ioChannel.write(buf);
                ioChannel.force(true);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
            return sizeDataWritten;
            
        }
        
        public int write(ByteBuffer buf, long position){
            int sizeDataWritten = 0;
            try {
                sizeDataWritten = ioChannel.write(buf, position);
                ioChannel.force(true);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
            return sizeDataWritten;
        }
        
        public long write(ByteBuffer[] bufs){
            long sizeDataWritten = 0;
            
            
            try {
                sizeDataWritten = ioChannel.write(bufs);
                ioChannel.force(true);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
            return sizeDataWritten;
        }
        
        public long write(ByteBuffer[] bufs, int offset, int length ){
            long sizeDataWritten = 0;
            try {
                sizeDataWritten = ioChannel.write(bufs, offset, length);
                ioChannel.force(true);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            
            return sizeDataWritten;
        }
        
        private void createDir(File file){
            File dir = new File(file.getParent());
            if (!dir.exists())                      // If directory does not exist
            {
                if (!dir.mkdir())                     // ...create it
                {
                    System.out.println("Cannot create directory: " + file);
                    System.exit(1);
                }
            } else if (!dir.isDirectory()) {
                System.err.println(file + " is not a directory");
                System.exit(1);
            }
        }
        
        //questo metodo non l'ho completato perche' gia' presente sulla classe InChannel
        //in quanto piu' naturale nel codice
        private long transferFrom(ReadableByteChannel src, long position, long count) throws IOException {
            return -1;
        }
        protected void implCloseChannel() throws IOException {
        }
        
        public FileChannel truncate(long size) throws IOException {
            return null;
        }
        
        
    }
    Nulla, ma e' sempre qualcosa.

  4. #4
    Utente di HTML.it
    Registrato dal
    Feb 2007
    Messaggi
    71
    Ciao, scusa sto cercando di fare quanto hai indicato tu nell'esmpio ma mi da un'eccezione
    java.nio.charset.UnsupportedCharsetException: IBM1047.

    Devo utilizzare qualche libreria particolare?

    Ciao

  5. #5
    Utente di HTML.it L'avatar di netarrow
    Registrato dal
    Apr 2004
    Messaggi
    1,425
    in quel codice feci tanto lavoro per nulla, basta fare così:

    byte[] ebcdicBytes = new String(asciiString).getBytes("IBM1047");

    se non ti trova la codifica mi fa strano, di solito è di default dentro il JRE, sicuro di star usando Java originale Sun o non fac-simile del gnu, microsoft o altri?
    Imparare è un'esperienza, tutto il resto è solo informazione. (Albert Einstein)

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.