java io流读写文件

一般遇到程序错误信息时我们都要写日志文件。

有些情况我们的程序经常更换配置信息,就需要写一个配置文件。

java中io提供了很好的方法。

写入文件方法:

//根据本类的路径获取文件

public class ErrorLogWrite {
 public static void logWrite(String log){
   try {
   
    String fileName=ErrorLogWrite.class.getResource("").getPath()+"service_error_log.txt"; 
    FileWriter writer = new FileWriter(fileName, true);//true 追加到末尾
    writer.write(log);
    writer.close();
    System.out.println(ErrorLogWrite.class.getResource("").getPath());
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
     
    }
 }

}

 

//读取文件。

//返回文件内容(services配置信息)

public static String getServicePath()
 {
  String FileName=ServicePath.class.getResource("").getPath()+"servicePath.properties";
        File myFile=new File(FileName);

       if(!myFile.exists())
        {

           //先判断一下文件是否存在如果不存在则创建
         try{
          myFile.createNewFile();
         }catch(Exception e){
          e.printStackTrace();
          System.out.println("文件不存在,创建失败!");
         }
        }
        try
        {
            BufferedReader in = new BufferedReader(new FileReader(myFile));
            String str;
           if((str = in.readLine()) != null) //也可以while循环读写数组
            {
                  return str;
            }
            in.close();
        }
        catch (IOException e)
        {
            e.getStackTrace();

             System.err.println("Can't Find " + FileName);

        }
        return "";
 }

}

 //还可以根据file.mkdirs();方法创建文件夹。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值