I am attempting to create a simple program that will keep a text log of collected data. To set this up, I have the following code run at the start of the program (to set up the log file, and the tools to use it):
File logFile = new File("logs/logFile.txt");
FileWriter fw;
FileReader fr;
BufferedWriter writer;
BufferedReader reader;
public void someMethod(){
System.out.println(logFile.getAbsolutePath());
try{
logFile.createNewFile();
}catch(Exception e){
System.err.println("WARNING: CANNOT CREATE FILE");
}
try{
fw = new FileWriter("plugins/Stalker/log.txt");
fr = new FileReader("plugins/Stalker/log.txt");
writer = new BufferedWriter(fw);
reader = new BufferedReader(fr);
} catch(Exception e){
System.err.println("ERROR: CANNOT READ OR WRITE TO LOG FILE");
}
}
When I run this, I hit both exceptions. It does not create either the file, or the folder (logs) at the path given in the first println. The path is as I expect it to be, and I SHOULD have write permissions for that directory (I know for a fact that other programs regularly write logs and such to a parent directory)... I've worked with files a little bit before, but it has been a bit, and I am at a complete loss here.
What sort of problem(s) might I be running into? What attempts at fixing this would you suggest?
You can use
exists
method available inFile
to test if it exists or not.If I remember correctly,
FileWriter
creates a file if it does not exist already. Check the other constructors for appending.However, I think the problem you are facing is because you haven't closed writing the file, before you attempt to read it.
Inorder to flush to the stream, you need to call close
Additionally, like Ravindra Gullapalli mentioned, you also need to check if the folder exist before attempting to create files. If not, you need to create them using mkdirs method.
When you are working with folders, you have to make sure that the folder exists.
For that you have to write a condition before
logFile.createNewFile();
to check whether the folder exists because createNewFild will not create folders.You have to modify the program little bit like this.