0

I'm trying this to overwrite the file:

File file = new File(importDir, dbFile.getName());
DataOutputStream output = new DataOutputStream(
new FileOutputStream(file, false));                 
output.close();

But it obviously overwrites an old file with an new empty one, and my goal is to owerwrite it with the content provided by file

How do I do that correctly?

Jacek Kwiecień
  • 12,397
  • 20
  • 85
  • 157

4 Answers4

1

Unfortunately, such simple operation as file copying is unobvious in Java.

In Java 7 you can use NIO util class Files as follows:

Files.copy(from, to);

Otherwise its harder and instead of tons of code, better read this carefully Standard concise way to copy a file in Java?

Community
  • 1
  • 1
mishadoff
  • 10,719
  • 2
  • 33
  • 55
0
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str;
    System.out.print("Enter a file name to copy : ");
    str = br.readLine();

    int i;
    FileInputStream f1;
    FileOutputStream f2;

  try
  {
    f1 = new FileInputStream(str);
    System.out.println("Input file opened.");
  }
  catch(FileNotFoundException e)
  {
    System.out.println("File not found.");
    return;
  }

  try
  {
    f2 = new FileOutputStream("out.txt");    //    <---   out.txt  is  newly created file
    System.out.println("Output file created.");
  }
  catch(FileNotFoundException e)
  {
    System.out.println("File not found.");
    return;
  }

  do
  {
    i = f1.read();
    if(i != -1) f2.write(i);
  }while(i != -1);
  f1.close();
  f2.close();
  System.out.println("File successfully copied");
Chintan Raghwani
  • 3,370
  • 4
  • 22
  • 33
0

You can use

FileOutputStream fos = new FileOutpurStream(file);

fos.write(string.getBytes());

constructor which will create the new file or if exists already then overwrite it...

Community
  • 1
  • 1
NullPointerException
  • 3,978
  • 4
  • 34
  • 52
0

For my purposes it seems that the easiest way is to delete file and then copy it

            if (appFile.exists()) {
                appFile.delete();
                appFile.createNewFile();
                this.copyFile(backupFile, appFile);
Jacek Kwiecień
  • 12,397
  • 20
  • 85
  • 157