Monday, January 27, 2014

Byte[]

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.DatatypeConverter;

public final class BytesStreamsAndFiles {

    private static final String INPUT_FILE_NAME = "C:\\Users\\abhinav\\Documents\\LTA.zip";

    private static final String OUTPUT_FILE_NAME = "C:\\Users\\abhinav\\Documents\\lta.txt.zip";

    private static final String OUTPUT_benc = "C:\\Users\\abhinav\\Documents\\lta.txt";

    public static void main(String... aArgs) {
        BytesStreamsAndFiles test = new BytesStreamsAndFiles();
        // read in the bytes
        byte[] fileContents = test.read(INPUT_FILE_NAME);

        String benc = DatatypeConverter.printBase64Binary(fileContents);
        // test.readAlternateImpl(INPUT_FILE_NAME);
        // write it back out to a different file name
        // test.write(fileContents, OUTPUT_FILE_NAME);

        log(benc.length());
        test.write2(benc, OUTPUT_benc);

        byte[] newFile = DatatypeConverter.parseBase64Binary(benc);

        test.write(newFile, OUTPUT_FILE_NAME);

        log("done...");

    }

    byte[] read(String aInputFileName) {
        log("Reading in binary file named : " + aInputFileName);
        File file = new File(aInputFileName);
        log("File size: " + file.length());
        byte[] result = new byte[(int)file.length()];
        try {
            InputStream input = null;
            try {
                int totalBytesRead = 0;
                input = new BufferedInputStream(new FileInputStream(file));
                while (totalBytesRead < result.length) {
                    int bytesRemaining = result.length - totalBytesRead;
                    // input.read() returns -1, 0, or more :
                    int bytesRead = input.read(result, totalBytesRead, bytesRemaining);
                    if (bytesRead > 0) {
                        totalBytesRead = totalBytesRead + bytesRead;
                    }
                }
                /*
                 * the above style is a bit tricky: it places bytes into the
                 * 'result' array; 'result' is an output parameter; the while
                 * loop usually has a single iteration only.
                 */
                log("Num bytes read: " + totalBytesRead);
            } finally {
                log("Closing input stream.");
                input.close();
            }
        } catch (FileNotFoundException ex) {
            log("File not found.");
        } catch (IOException ex) {
            log(ex);
        }
        return result;
    }

    /**
     * Write a byte array to the given file. Writing binary data is
     * significantly simpler than reading it.
     */
    void write2(String aInput, String aOutputFileName) {
        File file = new File(aOutputFileName);
        try {
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(aInput);
            bw.close();

            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void write(byte[] aInput, String aOutputFileName) {
        log("Writing binary file...");
        try {
            OutputStream output = null;
            try {
                output = new BufferedOutputStream(new FileOutputStream(aOutputFileName));
                output.write(aInput);
            } finally {
                output.close();
            }
        } catch (FileNotFoundException ex) {
            log("File not found.");
        } catch (IOException ex) {
            log(ex);
        }
    }

    /** Read the given binary file, and return its contents as a byte array. */
    byte[] readAlternateImpl(String aInputFileName) {
        log("Reading in binary file named : " + aInputFileName);
        File file = new File(aInputFileName);
        log("File size: " + file.length());
        byte[] result = null;
        try {
            InputStream input = new BufferedInputStream(new FileInputStream(file));
            result = readAndClose(input);
        } catch (FileNotFoundException ex) {
            log(ex);
        }
        return result;
    }

    /**
     * Read an input stream, and return it as a byte array. Sometimes the source
     * of bytes is an input stream instead of a file. This implementation closes
     * aInput after it's read.
     */
    byte[] readAndClose(InputStream aInput) {
        // carries the data from input to output :
        byte[] bucket = new byte[32 * 1024];
        ByteArrayOutputStream result = null;
        try {
            try {
                // Use buffering? No. Buffering avoids costly access to disk or
                // network;
                // buffering to an in-memory stream makes no sense.
                result = new ByteArrayOutputStream(bucket.length);
                int bytesRead = 0;
                while (bytesRead != -1) {
                    // aInput.read() returns -1, 0, or more :
                    bytesRead = aInput.read(bucket);
                    if (bytesRead > 0) {
                        result.write(bucket, 0, bytesRead);
                    }
                }
            } finally {
                aInput.close();
                // result.close(); this is a no-operation for
                // ByteArrayOutputStream
            }
        } catch (IOException ex) {
            log(ex);
        }
        return result.toByteArray();
    }

    private static void log(Object aThing) {
        System.out.println(String.valueOf(aThing));
    }
}


Ref: http://www.javapractices.com/topic/TopicAction.do?Id=245

Tuesday, January 14, 2014

ANT - JAVA CREATE JAR - Reference JARS dynamically

Example 1

<project name="DataLoader"
    basedir="."
    default="main">
    <property name="src.dir"
        value="src"/>
    <property name="build.dir"
        value="build"/>
    <property name="classes.dir"
        value="${build.dir}/classes"/>
    <property name="jar.dir"
        value="${build.dir}/jar"/>
    <property name="main-class"
        value="EntryPoint"/>
    <property name="lib.dir"
        value="libs"/>
    <!--     <path id="build.classpath"> -->
    <!--         <fileset dir="${lib.dir}" includes="**/*.jar"/> -->
    <!--     </path> -->
    <path id="build.classpath">
        <fileset dir="libs">
            <include name="**/*.jar"/>
        </fileset>
    </path>
    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>
    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <mkdir dir="${jar.dir}"/>
        <javac srcdir="${src.dir}"
            destdir="${classes.dir}"
            classpathref="build.classpath"/>
    </target>
    <!--     <target name="run" depends="jar"> -->
    <!--         <java fork="true" classname="${main-class}"> -->
    <!--             <classpath> -->
    <!--                 <path refid="classpath"/> -->
    <!--                 <path location="${jar.dir}/${ant.project.name}.jar"/> -->
    <!--             </classpath> -->
    <!--         </java> -->
    <!--     </target> -->
    <target name="package"
        depends="compile">
        <echo>=== PACKAGE ===</echo>
        <!-- convert build.classpath to mf.classpath (the string needed for the manifest task) -->
        <pathconvert property="mf.classpath"
            pathsep=" ">
            <path refid="build.classpath"/>
            <flattenmapper/>
        </pathconvert>
        <!-- now build the manifest file, using mf.classpath -->
        <tstamp/>
        <!-- needed for TODAY -->
        <manifest file="MANIFEST.MF">
            <attribute name="Built-By"
                value="AbhinavSharma"/>
            <attribute name="Created-By"
                value="AbhinavSharma"/>
            <attribute name="Main-Class"
                value="${main-class}"/>
            <attribute name="Class-Path"
                value="${mf.classpath}"/>
        </manifest>
        <!-- create the jar file, including the manifest file we just created -->
        <jar basedir="${classes.dir}"
            destfile="${jar.dir}/Dol.jar"
            includes="**/*.*"
            excludes="**/*Test*"
            manifest="MANIFEST.MF"/>
        <!-- copy all the jar files out to the destination directory (dest.dir) -->
        <copy todir="${jar.dir}">
            <fileset dir="${lib.dir}">
                <exclude name="junit*"/>
                <include name="*.jar"/>
                <include name="*.zip"/>
            </fileset>
        </copy>
        <!-- move this file before the 'jar' task (and put it in the 'classes' dir) if you'd rather
             include it in the jar -->
        <!--         <copy file="${resources.dir}/log4j.properties" tofile="${dest.dir}/log4j.properties" overwrite="true" /> -->
        <!--         <copy file="${resources.dir}/${properties.file}" tofile="${dest.dir}/${properties.file}" overwrite="true" /> -->
        <!--         <delete dir="${dest.dir.classes}" /> -->
    </target>
    <target name="main"
        depends="clean, package"/>
</project>



Example 2



<!-- First, I create my classpath (build.classpath) from all the jar files in my lib directory -->
<path id="build.classpath">
    <fileset dir="libs">
        <include name="**/*.jar" />
    </fileset>
</path>
<!-- Next, my package task uses that classpath -->
<target name="package" depends="compile">
    <echo>=== PACKAGE ===</echo>
    <!-- convert build.classpath to mf.classpath (the string needed for the manifest task) -->
    <pathconvert property="mf.classpath" pathsep=" ">
        <path refid="build.classpath" />
        <flattenmapper />
    </pathconvert>
    <!-- now build the manifest file, using mf.classpath -->
    <tstamp/><!-- needed for TODAY -->
    <manifest file="MANIFEST.MF">
        <attribute name="Built-By" value="${manifest.built.by}"/>
        <attribute name="Created-By" value="${manifest.created.by}"/>
        <attribute name="Main-Class" value="${manifest.main.class}"/>
        <attribute name="Implementation-Version" value="${version.number}-b${build.number}"/>
        <attribute name="Built-Date" value="${TODAY}"/>
        <attribute name="Class-Path" value="${mf.classpath}" />
    </manifest>
    <!-- create the jar file, including the manifest file we just created -->
    <jar basedir="${dest.dir.classes}"
        destfile="${package.file}"
        includes="**/*.*"
        excludes="**/*Test*"
        manifest="MANIFEST.MF" />
    <!-- copy all the jar files out to the destination directory (dest.dir) -->
    <copy todir="${dest.dir}">
        <fileset dir="${lib.dir}">
            <exclude name="junit*" />
            <include name="*.jar"/>
            <include name="*.zip"/>
        </fileset>
    </copy>
    <!-- move this file before the 'jar' task (and put it in the 'classes' dir) if you'd rather
         include it in the jar -->
    <copy file="${resources.dir}/log4j.properties" tofile="${dest.dir}/log4j.properties" overwrite="true" />
    <copy file="${resources.dir}/${properties.file}" tofile="${dest.dir}/${properties.file}" overwrite="true" />
    <delete dir="${dest.dir.classes}" />
</target>