user2281498 user2281498 - 11 months ago 55
Java Question

Unable to write to the file, Created in java using File class

Class MakeDirectory contains the constructor and in constructor i created a directory and inside that directory i created a file. But i am unable to write anything to the newly created file. Though file and directory has been generated successfully. can anyone help me over it why i am not able to write to the file Anything.txt.

public class MakeDirectory {

MakeDirectory() throws IOException{
// Creates Directory
File mydir= new File("MyDir");

// Creates new file object
File myfile = new File("MyDir","Anyfile.txt");

//Create actual file Anyfile.txt inside the directory
PrintWriter pr= new PrintWriter(myfile);
pr.write("This file is created through java");
public static void main(String args[]) throws IOException {
new MakeDirectory();


Answer Source

If you want to use PrintWriter you need to know that it is not automatically flushing. After you write you need to flush. Also, don't forget to close your PrintWriter!

PrintWriter pw = new PrintWriter(myFile);