第十五周课堂练习补交

课题:编写MyOD.java 用java MyOD XXX实现Linux下od -tx -tc XXX的功能

实验代码

import java.io.*;

public class Hextext
{
    public static void main( String[] args ) throws Exception
    {
        // argument check
        if ( args.length < 1 )
        {
            println( "not enough arguments!" );
            printUsage();
        }
        if (!( new File( args[0] ).exists() ) )
        {
            println("assigned file doesnot exist!");
        }
        
        // parameters
        File srcfile = new File( args[0] );
        File destfile = new File( srcfile.getAbsolutePath() + ".hextext" );
        final int NUM_OF_CHAR_PER_LINE = 8;
        FileInputStream fin = new FileInputStream( srcfile );
        PrintWriter fout = new PrintWriter( new FileWriter( destfile ) );
        
        // transfer
        byte[] chunk = new byte[ NUM_OF_CHAR_PER_LINE ];
        int rdcnt = 0;
        
        
        while ( ( rdcnt = fin.read( chunk ) ) != -1 )
        {
            // init line buf
            char[] line_buf = new char[ NUM_OF_CHAR_PER_LINE * 3 + 1 + NUM_OF_CHAR_PER_LINE * 2 ];
            for ( int i=0; i<line_buf.length; ++i ) 
            { 
                line_buf[i] = ' '; 
                line_buf[ NUM_OF_CHAR_PER_LINE * 3 ] = '|';
            }
            // write into line buf
            for ( int i=0; i<rdcnt; ++i )
            {
                char[] hexd = toHextextByte( (int)chunk[i] ).toCharArray();
                line_buf[ i*3 ] = hexd[0];
                line_buf[ i*3+1 ] = hexd[1];
                line_buf[ NUM_OF_CHAR_PER_LINE * 3 + 1 + i*2 ] = (char)chunk[i];
            }
            // write line buf
            fout.println( line_buf );
        }
        
        fin.close();
        fout.close();
        
        // report
        println( "Transfer Successfully to File:" );
        println( destfile.getAbsolutePath() );
    }
    
    public static String toHextextByte( int nch )
    {
        String ret = Integer.toHexString( nch );
        int len = ret.length();
        if ( len == 1 )
        {
            ret = "0" + ret;
        }
        else if ( len > 2 )
        {
            ret = ret.substring( len-2 );
        }
        return ret;
    }
    
    public static void println( Object o )
    {
        System.out.println( o );
    }
    
    public static void printUsage()
    {
        println("Usage:");
        println("Hextext file_path");
        println("");
    }    
}

实验运行结果截图

码云链接

原文地址:https://www.cnblogs.com/LeeX1997/p/6924346.html