java程序如何产生io异常,Java文件IO异常

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");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值