zoukankan      html  css  js  c++  java
  • 使用getResourceAsStream

    很多时候都要读取文件,于是想到了getResourceAsStream

    这是网上说的:

    在使用Class.getResourceAsStream 时, 资源路径有两种方式, 一种以 / 开头,则这样的路径是指定绝对
    路径, 如果不以 / 开头, 则路径是相对与这个class所在的包的。  

    在使用ClassLoader.getResourceAsStream时, 路径直接使用相对于classpath的绝对路径。


    于是自己写个demo来实践下

     

     

     

    代码
    package jdk.resource;

    import java.io.InputStream;

    /**
    *
    @author <a href="mailto:zhangting@taobao.com">张挺</a>
    *
    @since 2010-3-26 11:19:04
    */
    public class GetFileDemo {
    public static void main(String[] args) {
    GetFileDemo demo
    = new GetFileDemo();
    InputStream stream
    = demo.getClass().getResourceAsStream("/a.txt");
    try {
    System.out.println(stream.available());
    }
    catch (Exception e) {
    System.out.println(
    "can't find file");
    }

    InputStream stream1
    = GetFileDemo.class.getResourceAsStream("/a.txt");
    try {
    System.out.println(stream1.available());
    }
    catch (Exception e) {
    System.out.println(
    "can't find file");
    }

    InputStream stream2
    = ClassLoader.getSystemResourceAsStream("a.txt");
    try {
    System.out.println(stream2.available());
    }
    catch (Exception e) {
    System.out.println(
    "can't find file");
    }
    }
    }

    a.txt的路径为classpath的根目录。


    class如果不加"/"就会以当前路径为主,以相对路径方式,意味着我不加"/"会查找jdk/resource/a.txt

    如果加了"/"就会从classpath下查找

    ClassLoader的查找默认就是以classpath开始的绝对路径,不能加"/",否则会找不到文件

  • 相关阅读:
    hdu 3367 Pseudoforest
    hdu 2489 Minimal Ratio Tree
    hdu 4009 Transfer water
    poj 3164 Command Network
    hdu 3926 Hand in Hand
    hdu 3938 Portal
    5-26日(面经总结)
    5-25日
    5-21日|5-22日
    5-13日记录|5-14日
  • 原文地址:https://www.cnblogs.com/xiziyin/p/1696889.html
Copyright © 2011-2022 走看看