更新时间:2023-01-18 18:04:45
使用文件夹时,必须确保该文件夹存在。
When you are working with folders, you have to make sure that the folder exists.
为此你必须在 logFile.createNewFile();
之前写一个条件来检查文件夹是否存在因为createNewFild不会创建文件夹。
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");
}
}