File Copy In Java



package com.vz.ant.task;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCopy {
 public static void main(String[] args) {
   if (args.length != 2)    // Check arguments
     System.err.println("Usage: java FileCopy  ");
   else {
     try { copy(args[0], args[1]); }
     catch (IOException e) { System.err.println(e.getMessage()); }
   }
 }

 public static void copy(String from_name, String to_name) throws IOException{
   File from_file = new File(from_name);  // Get File objects from Strings
   File to_file = new File(to_name);
   if (!from_file.exists())
     abort("FileCopy: no such source file: " + from_name);
   if (!from_file.isFile())
     abort("FileCopy: can't copy directory: " + from_name);
   if (!from_file.canRead())
     abort("FileCopy: source file is unreadable: " + from_name);

   if (to_file.isDirectory())
     to_file = new File(to_file, from_file.getName());

   if (to_file.exists()) {
     if (!to_file.canWrite())
       abort("FileCopy: destination file is unwriteable: " + to_name);
     System.out.print("Overwrite existing file " + to_name + "? (Y/N): ");
     System.out.flush();
     BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
     String response = in.readLine();
     if (!response.equals("Y") && !response.equals("y"))
       abort("FileCopy: existing file was not overwritten.");
   }
   else {
     String parent = to_file.getParent();  // Get the destination directory
     if (parent == null) parent = System.getProperty("user.dir"); // or CWD
     File dir = new File(parent);          // Convert it to a file.
     if (!dir.exists())
       abort("FileCopy: destination directory doesn't exist: " + parent);
     if (dir.isFile())
       abort("FileCopy: destination is not a directory: " + parent);
     if (!dir.canWrite())
       abort("FileCopy: destination directory is unwriteable: " + parent);
   }

   FileInputStream from = null;  // Stream to read from source
   FileOutputStream to = null;   // Stream to write to destination
   try {
     from = new FileInputStream(from_file);  // Create input stream
     to = new FileOutputStream(to_file);     // Create output stream
     byte[] buffer = new byte[4096];         // A buffer to hold file contents
     int bytes_read;                         // How many bytes in buffer
     while((bytes_read = from.read(buffer)) != -1) // Read bytes until EOF
       to.write(buffer, 0, bytes_read);            //   write bytes
   }
   finally {
     if (from != null) try { from.close(); } catch (IOException e) { ; }
     if (to != null) try { to.close(); } catch (IOException e) { ; }
   }
 }

 private static void abort(String msg) throws IOException {
   throw new IOException(msg);
 }
}

String to formatted XML conversion



import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class StringToXML {
 public static String strT0XML(String xmlString) {
  try {
   DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
   Document document = documentBuilder.parse(inputStream);
   TransformerFactory tfactory = TransformerFactory.newInstance();
   DOMSource xmlSource = new DOMSource(document);
   java.io.StringWriter writer = new StringWriter();
   javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(writer);
   Transformer serializer = tfactory.newTransformer();
   serializer.setOutputProperty(OutputKeys.INDENT, "yes");
   serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
   serializer.transform(xmlSource, result);
   return writer.toString();
  } catch (TransformerException e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return "";
 }
}


AspectJ Example
------------------

TestAspect.java
----------------

package com.aspectj;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.JoinPoint;

@Aspect
public class TestAspect {

    @Before("execution (* com.aspectj.TestTarget.test*(..))")
    public void advice(JoinPoint joinPoint) {
        System.out.printf("TestAspect.advice() called on '%s'%n", joinPoint);
    }
}


TestTarget.java
-----------------

package com.aspectj;

public class TestTarget {

    public static void main(String[] args) {
        System.out.println("----------------------->--------- Start test -----------<---------------------");
        new TestTarget().test();
        System.out.println("----------------------->--------- End test -----------<---------------------");
    }

    public void test() {
        System.out.println("TestTarget.test()");
    }
}



aop.xml   - keep this file in META-INF 
----------------------------------------

<aspectj>
    <aspects>
        <aspect name="com.aspectj.TestAspect"/>
    </aspects>

    <weaver options="-verbose">
        <include within="com.aspectj.*"/>
    </weaver>
</aspectj>



build.xml
---------

<?xml version="1.0"?>
<project name="aspectj-example" xmlns:aspectj="antlib:org.aspectj">

    <property name="src.dir" value="src/main/java"/>
    <property name="resource.dir" value="src/main/resources"/>
    <property name="target.dir" value="target"/>
    <property name="classes.dir" value="${target.dir}/classes"/>

    <taskdef uri="antlib:org.aspectj"
            resource="org/aspectj/antlib.xml"
            classpath="${resource.dir}/aspectjtools.jar"/>

    <path id="aspectj.libs">
        <fileset dir="${resource.dir}"/>
    </path>

    <target name="clean">
        <delete dir="${target.dir}"/>
        <mkdir dir="${target.dir}"/>
        <mkdir dir="${classes.dir}"/>
    </target>

    <target name="compiletime" depends="clean">
        <aspectj:iajc source="1.5" srcdir="${src.dir}" classpathref="aspectj.libs" destDir="${classes.dir}"/>
        <java classname="com.aspectj.TestTarget" fork="true">
            <classpath>
                <path refid="aspectj.libs"/>
                <pathelement path="${classes.dir}"/>
            </classpath>
        </java>
    </target>

    <target name="postcompile" depends="clean">

        <echo message="Compiling..."/>
        <javac debug="true" srcdir="${src.dir}" classpathref="aspectj.libs" destdir="${classes.dir}"/>

        <echo message="Weaving..."/>
        <aspectj:iajc classpathref="aspectj.libs" inpath="${classes.dir}" aspectpath="${src.dir}" outJar="${classes.dir}/test.jar"/>

        <echo message="Running..."/>
        <java classname="com.aspectj.TestTarget" fork="true">
            <classpath>
                <path refid="aspectj.libs"/>
                <pathelement path="${classes.dir}/test.jar"/>
            </classpath>
        </java>

    </target>

    <target name="loadtime" depends="clean">

        <echo message="Compiling..."/>
        <javac debug="true" srcdir="${src.dir}" classpathref="aspectj.libs" destdir="${classes.dir}"/>

        <echo message="Running..."/>
        <java classname="com.aspectj.TestTarget" fork="true">
            <jvmarg value="-javaagent:${resource.dir}/aspectjweaver.jar"/>
            <classpath>
                <path refid="aspectj.libs"/>
                <pathelement path="${classes.dir}"/>
                <pathelement path="${resource.dir}"/>
            </classpath>
        </java>

    </target>

</project>



pom.xml
-----------

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test.aspectj</groupId>
    <artifactId>test</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>test</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>com.aspectj.TestTarget</mainClass>
                </configuration>
            </plugin>
        </plugins>    </build>
</project>

and keep the below jar files under classpath and resource dir for build to run
aspectjrt.jar,aspectjtools.jar,aspectjweaver.jar

thanks
Anil.E