在项目中根据配置文件路径生成File对象的方法

File类最常用的构造方法有两个,File(String pathname) 及File(URI uri) ,其中最最常用的构造方法是File(String pathname),其中这个字符串参数值得探讨一下:

源码中注释是这样写的:

/**
     * Creates a new <code>File</code> instance by converting the given
     * pathname string into an abstract pathname.  If the given string is
     * the empty string, then the result is the empty abstract pathname.
     *
     * @param   pathname  A pathname string
     * @throws  NullPointerException
     *          If the <code>pathname</code> argument is <code>null</code>
     */
    public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

意思就是说,字符串参数如果是空字符串的话,就返回一个空的抽象路径;如果是null的话,就抛空指针异常。

@Test
	public void testFilePathName() {
		File file = null;
		file = new File("");
		System.out.println(file.getAbsolutePath());
		// 打印D:\workspace\test

		file = new File("/");
		System.out.println(file.getAbsolutePath());
		// 打印D:\

		String pathName = "/test/src/main/resources/dd.txt";
		file = new File(pathName);
		System.out.println(file.getAbsolutePath());
		// 打印D:\test\src\main\resources\dd.txt

		file = new File("test/src/main/resources/dd.txt");
		System.out.println(file.getAbsolutePath());
		// 打印D:\workspace\test\test\src\main\resources\dd.txt

		file = new File("/src/main/resources/dd.txt");
		System.out.println(file.getAbsolutePath());
		// 打印D:\src\main\resources\dd.txt

		file = new File("src/main/resources/dd.txt");
		System.out.println(file.getAbsolutePath());
		// 打印D:\workspace\test\src\main\resources\dd.txt
	}
如果字符串参数的路径名是相对路径,即不带盘符的情况下,默认情况下,系统是根据用户的工作路径来解释相对路径的。何为工作路径?System.getProperty("user.dir")的值。简单来讲就是这个项目所在的路径,本项目就放在D盘workspace文件夹下,项目名是test,所以工作路径就是D:\workspace\test2。

如果字符串参数是空字符串的话,构造方法返回的还是工作路径;如果是一个单斜杠"/"的话,返回的是项目所在盘的根路径,如D:\;如果传配置文件的限定名的话(右键,Copy Qualified Name得到的值,注意是以斜杠开始的),会发现返回的路径名字符串包含了重复的项目名;去掉/projectName之后传入(此时是以单斜杠开始的字符串),发现返回的路径竟然是根路径加所传的字符串参数;接着把字符串参数开始的单斜杠去掉,传入后返回正确的路径名。所以,传入的字符串参数应该是Qualified Name去掉/projectName/,注意不是以单斜杠开始的,否则会跑到根路径去的!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值