Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to experiment with the whole idea of creating two text files then write to one of them, rename the second file with the first file and then deleting the first file. I have a school project where i need to apply this concept. So, before i actually applied the concept in my project, I tried to experiment with a rough code. Now, everything works fine except that the second file doesn't contain the data from the first file. How do i fix this problem?

This is my class which is called potpie:-

Java
package project4;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class potpie {
	
	PrintWriter out,cr;
	
	File file1 = new File("trial.txt");
	File file2 = new File("item.txt");
	
	public void createfile() throws IOException
	{
		out = new PrintWriter(new FileWriter(file1,true));

		out.println("User1" + "639755");

		cr = new PrintWriter(new FileWriter(file2,true));
        cr.close();
        out.close();
		file1.delete();
		file2.renameTo(file1);

}

}

I am getting blank output in my trial.txt file and i don't know where i made the mistake. Please help me out.
Posted
Updated 23-May-15 7:57am
v2

1 solution

What would you expect? You tried to write something only to file1, not to file2. But you deleted file1, so its content is lost. Then you renamed empty file2 to file1

Just in case: please, don't ask "what should I do?". To ask such question, you should have explained what you wanted to achieve, which you did not explain. But I can answer to it right now: just use your head, elementary logic; also, read the documentation thoroughly; it is very clean.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900