Search code examples
javafile-ioobjectinputstream

Java copying files to a new path doesn´t work


I have another question. Right now I am writing a little program, which runs on my pc and on my laptop. These two programs communicate with each other. I can write Strings (like a chat) and I want to send files. This little chat works, but the files are making problems right now. Which makes me a little bit wondering, because I got it already running some days ago. But now it isn't working (can't remember that I changed important things). Unfortunately I cant undo because Eclipse was already closed.

So I was looking for the mistake but I couldn't find it since hours. I hope you can help me.

Situation:

I choose a file at my pc/laptop and send it to my laptop/pc (I send the text [Strings] on the same way as the files and it works). The receiver shall save the file at a directory (targetPath - it is defined somewhere else in the code. It is a folder on my desktop). So I get the file as an Object from a "ObjectInputStream" and cast it as a "File":

 if(msg instanceof File){ //msg is the object I got from the ObjectInputStream
                        //its a file
                        model.copyFileTo((File) msg);
}

this is the method which makes trouble:

    public void copyFileTo(File file) throws IOException{
            System.out.println(file.getName());//this is just a test and it works. It prints out the name of the sended file
    if(targetPath.toFile().exists()){
        if(file.exists()){
            Path temp = Paths.get(targetPath+"/"+file.getName());
            if(!temp.toFile().exists()){
                Files.copy( file.toPath(), temp,  StandardCopyOption.REPLACE_EXISTING);
                System.out.println("copied");
            }else{
                System.out.println("File already exists");
            }
        }else{
            System.out.println("File doesnt exists");
        }
    }else{
        System.out.println("targetPath doesnt exists!");
    }
}

I do not become an error, but it prints "File doesn't exists", so something at "if(file.exists())" goes wrong. If I cut this part out the program hangs up at Files.copy(...), which I know because it doesn't print out "copied".


Solution

  • On the source system, you'd do something like this (Java 7):

    Path path = Paths.get("C:\\MyFolder", "MyFile.bin");
    byte[] fileContent = Files.readAllBytes(path);
    // send fileContent to target system
    

    On the target system, you'd do:

    // receive fileContent from source system
    Path path = Paths.get("C:\\Where\\To\\Store\\File", "MyFile.bin");
    Files.write(path, fileContent);
    

    In Java 6 or lower, you'd use a File object instead of the Path object and copy bytes yourself.