Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. package copyfile;
  2.  
  3. /*
  4. * This program accepts two filenames either at
  5. * the command-line or in the source code itself.
  6. *
  7. * To use this program in the command-line:
  8. *
  9. * java CopyFile filename1 filename2
  10. *
  11. * Otherwise, just type in the path to both filenames
  12. * in the source code.
  13. *
  14. * If the second file does not exist,
  15. * the program will create the file.
  16. */
  17.  
  18. import java.io.*;
  19.  
  20. // Copies a file to another file.
  21. class CopyFile {
  22. public static void main(String args[]) {
  23. String first;
  24. String second;
  25. String line;
  26.  
  27. // Sets first and second using either command-line or source code
  28. if(args.length == 2) {
  29. first = args[0];
  30. second = args[1];
  31. } else {
  32. first = "src/copyfile/first.txt";
  33. second = "src/copyfile/second.txt";
  34. }
  35.  
  36. // Tries to read and write from first to second.
  37. try(BufferedReader br = new BufferedReader(
  38. new FileReader(first));
  39. FileWriter fw = new FileWriter(second)) {
  40.  
  41. do {
  42. line = br.readLine();
  43.  
  44. if(line != null) {
  45. fw.write(line);
  46. }
  47. } while(line != null);
  48. } catch(FileNotFoundException exc) {
  49. System.out.println("FileNotFound Exception: File not found!");
  50. return;
  51. } catch(IOException exc) {
  52. System.out.println("I/O Exception: " + exc);
  53. return;
  54. }
  55.  
  56. System.out.println("Successfully copied file!");
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement