Last active
September 7, 2020 18:28
-
-
Save diegozr1/e68dd1ebcbcb63d5b4bb to your computer and use it in GitHub Desktop.
A program for copying a text file using Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
[Api Call Example "Copy a file"] | |
== How to run it == | |
1 - Compile it | |
javac copy.java | |
2 - Run it | |
java copy [source] [destiny] | |
** [source] is the path to the original file | |
** [destiny] is the path where the file will be copied | |
Enjoy it! | |
*/ | |
import java.io.*; | |
public class copy{ | |
public copy(String source, String destiny){ | |
System.out.println("Copying from "+source+ " to " + destiny); | |
if(this.startCopy(source, destiny)){ | |
System.out.println("Copy successful from "+destiny+" to "+destiny+"!"); | |
}else{ | |
System.out.println("An unkown error has ocurred!"); | |
} | |
} | |
public boolean startCopy(String source, String destiny){ | |
//Checar si destiny existe como archivo | |
String line = null; | |
try{ | |
BufferedReader br = new BufferedReader(new FileReader(source)); | |
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(destiny))); | |
while ((line = br.readLine()) != null) { | |
//System.out.println(line); | |
out.write(line+"\n"); | |
} | |
br.close(); | |
out.close(); | |
}catch(Exception e){ | |
e.printStackTrace(); | |
return false; | |
} | |
return true; | |
} | |
public static boolean validate(String[] args){ | |
if(args.length>1){ | |
File source = new File(args[0]); | |
File destiny = new File(args[1]); | |
if(source.exists() && !source.isDirectory() ) { | |
if(!destiny.exists() && !destiny.isDirectory() ) { | |
return true; | |
}else{ | |
System.out.println("Error, destiny file "+destiny+" already exists, try again \n"); | |
return false; | |
} | |
}else{ | |
System.out.println("Error, source file "+source+" doesn't exists, try again \n"); | |
return false; | |
} | |
} | |
return false; | |
} | |
public static void main(String[] args) { | |
if(validate(args)){ | |
copy cp = new copy(args[0], args[1]); | |
}else{ | |
System.out.println("How it works, type: \n 'java copy \t [Path to source file] \t [Path to the destiny] ' \nin your terminal \n\nBuilt by Diego Zamora Rodríguez <a01227598>\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment