Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am trying to create a program able to copy a file from one directory to another, but I need to ask the user to select the file, and input the directory. How do i do that?

This is what I have done so far:

import java.io.*;


public class FileCopy {

  public static void main(String[] args) {

      File file = new File(".");
      File copyfile = new File(".");

      BufferedReader reader;
      PrintWriter writer;
      String line;

      try{
          if (copyfile.createNewFile() || !copyfile.createNewFile()) {
              reader = new BufferedReader (new FileReader(file));
              writer = new PrintWriter(new FileWriter(copyfile));
            while ((line = reader.readLine()) !=null){
                writer.println(line);
                }
            reader.close();
            writer.close();

            }
      }catch(IOException ioEx){
          System.err.println("I could not copy the file to a destination directory");

      }
    enter code here

  }
}
share|improve this question

You can use command-line arguments for user to enter the file name and the destination directory. To do so write something like the following:

public static void main(String[] args) {
    if (args.length == 0 || args.length > 2) {
        System.err.println("Invalid arguments, enter a file path and a destination directory.");
    }

    File file = new File(args[0]);
    if (!file.isFile()) {
        System.err.println("First argument must be a file.");
    }
    if (!new File(args[1]).isDirectory()) {
        System.err.println("Second argument must be a directory");
    }

    File copyfile = new File(args[1], file.getName());
    ...

Besides that, you don't have to create a new file with copyfile.createNewFile(), the FileWriter(File file) constructor does it for you. In addition, code like if (copyfile.createNewFile() || !copyfile.createNewFile()) { ... does not look good, because it gets inside the if statement either ways, you could just call copyfile.createNewFile().

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.