Reputation: 12637
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?
Upvotes: 0
Views: 119
Reputation: 12637
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);
Upvotes: 0
Reputation: 10789
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?
Upvotes: 1
Reputation: 4008
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...
Upvotes: 0
Reputation: 3370
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");
Upvotes: 0