读取配置文件

类加载器
1、直接用Class.ForName(类的路径名)

  Class.forName("com.hsf.ClassLoader.ClassLoader");

2、用ClassLoder (类加载器)

 InputStream in = ClassLoader.getSystemResourceAsStream("aa.txt");
         byte[] bs= new byte[1024];
          try {
            int len=in.read(bs);
            //把字节转换成String
            System.out.println(new String(bs,0,len));
        } catch (IOException e) {
            e.printStackTrace();
        }```

小知识点:
1、把字节转换成String

System.out.println(new String(bs,0,len));

2、将String转换成字节数组

String string="aaaa";
byte[] bytes = string.getBytes();

配置文件的读写
数据库的账号和密码可能会发生变更,所以这些都不应该写在程序中,而应该写在配置文件中,读取配置文件,这样修改起来也比较方便。
以下是读取配置文件的代码:

static
  {
    try
    {
      Properties properties = new Properties();
      //  JdbcUtil.class.getClassLoader();
       InputStream in =JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
       System.out.println("in="+in);
      //InputStream in = ClassLoader.getResourceAsStream("jdbc.properties");
      //装载文件
       properties.load(in);     
       forName = properties.getProperty("forName");
       url = properties.getProperty("url");
       username = properties.getProperty("username");
       password = properties.getProperty("password");

      //不需要每次都加载一次驱动
      Class.forName(forName);      
    } catch (Exception e) {
       e.printStackTrace();
     }
   }

注意:配置文件里面字符串一定不要用“”,在写的过程中由于password为空,在配置文件里面写成了password =“”,所以就报了数据库连接错误。还有就是 InputStream in =JdbcUtil.class.getClassLoader().getResourceAsStream(“jdbc.properties”); 这里一定不能写成getSystemResourceAsStream。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值