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?
解决方案
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.
File logFileFolder = new File("logs");
File stalkerFolder = new File("plugins/Stalker");
File logFile = new File("logs/logFile.txt");
FileWriter fw;
FileReader fr;
BufferedWriter writer;
BufferedReader reader;
public void someMethod(){
System.out.println(logFile.getAbsolutePath());
try{
if (!logFileFolder.exists()){
// Create folder if does not exist
logFileFolder.mkdir();
}
logFile.createNewFile();
}catch(Exception e){
System.err.println("WARNING: CANNOT CREATE FILE");
}
try{
if (!stalkerFolder.exists()){
// Create folders if does not exist
stalkerFolder.mkdirs();
}
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");
}
}