0

So here is the code, where the program runs but function is not being performed. Is it possible to copy a file in Java like this or should I use different method? If so, any references would be helpful.

import java.io.*;
import java.util.*;
import java.lang.*;
 public class test
{
    public static void main(String[] args) 
    {

        String path = "cmd /C cd C:/xamppy/htdocs/fuzzy/includes/xxxxx"; 


        String command = "cmd /C copy \"C:/xamppy/htdocs/fuzzy/includes/xxxxx/lifelesson.jpg\" \"C:/xamppy/htdocs/fuzzy/searcheditems\"";       
        try{
            Runtime.getRuntime().exec(path);
        Runtime.getRuntime().exec(command);
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
    }
}
Mikhail Antonov
  • 1,297
  • 3
  • 21
  • 29
  • 3
    Possible duplicate of [Move / Copy File Operations in Java](http://stackoverflow.com/questions/300559/move-copy-file-operations-in-java) – Mikhail Antonov Apr 12 '17 at 04:39

1 Answers1

0

In java you can copy files using FileOuputStream and FileInputStream. Here is short demo:

public static void main(String[] args) throws IOException {
        File file = new File("C:\\createtable.sql");
        File copy = new File("C:\\copy.sql");

        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(copy);

        byte[] buffer = new byte[1024];

        int length;
        // copy the file content in bytes
        while ((length = fis.read(buffer)) > 0) {

            fos.write(buffer, 0, length);

        }

        fis.close();
        fos.close();

        System.out.println("File is copied successful!");
    }

At first it creates two file file and copy. And byte array buffer which holds content of file read from FileInputStream and written into FileOutputStream.

Jay Smith
  • 2,331
  • 3
  • 16
  • 27
  • If you do it that way, it would be also nice to use [try-with-resources](https://stackoverflow.com/questions/26516020/try-with-resources-vs-try-catch) to handle exceptions and release resources properly. Just saying to inform @SaumyaSharma about good practices. – Mikhail Antonov Apr 12 '17 at 05:18
  • As per this code, the file content is copied from one file to another. However, I don't have any such temporary file. So is there a way to create new file using java and then copy the contents there? –  Apr 12 '17 at 05:36
  • `createNewFile` method of `File` class can be used – Jay Smith Apr 12 '17 at 05:38