0

I am trying to make this program that will write a file to the users computer but am having trouble really, I want to write a file called desktop.bat that I have to the c:/ directory but it doesn't seem like it's working. this is the code:

package javawriter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class JavaWriterObject {

    public void TryThis(){
    try{

        File file = new File("C:\\Desktop.bat");

        if (file.exists()){
                System.out.println("The file exists \ndirectory is found");
        }else{
            System.out.println("file is not found yet ".concat("file will be created"));
            file.createNewFile();
        }

        FileWriter out = new FileWriter(file);
        BufferedWriter writer = new BufferedWriter(out);
        writer.write();

        writer.close();

        }catch(IOException e){
                e.printStackTrace();
        }
   }
}

Do I have to write a String for the writer.write(); or can I do something where I can write the file I want instead?

Walid
  • 73
  • 1
  • 1
  • 9

2 Answers2

3

Java 7's Files.copy method helps you copy a file from one location to another.

If you're using an older version of Java, you will need to either read the original file in yourself and copy its contents into your new file, or you'll have to use a third-party library. See the answers to this question for several good solutions, including using Apache Commons IO FileUtils or just the standard Java API.

Once you've decided how you want to copy the file, you might run into another problem. By default, Windows 7 will prevent you from writing to certain directories such as C:\. You can try writing to a different directory, such as in the temp directory or any location within the user's home directory. If you must write to C:\, the easiest solution (aside from creating the file ahead of time in Windows and overwriting it in your program, which probably defeats the purpose) is to disable UAC and make sure your user account has write permission on that directory--but this, of course, has security implications.

Community
  • 1
  • 1
rob
  • 6,147
  • 2
  • 37
  • 56
1

You have to get the content you want to write from somewhere, either a String literal in your application, or, the preferred method would be from a resource (bundled along with your application) via. YourClass.class.getResourceAsStream(name).

Copying an input stream to a file is a bit of effort, Guava can copy, but, if you're using Guava, you may as well copy directly from the resource to the file.

FauxFaux
  • 2,445
  • 16
  • 20