文件分隔符、几种创建File对象的方式

1. 分隔符:

* 路径分隔符:pathSeparator --> ;
* 名称分隔符:separator --> windows(\),linux等(/)

public static void main(String[] args) {
		
		String str = File.pathSeparator;
		String str2 = File.separator;
		System.out.println(str);// Output: ;
		System.out.println(str2);// Output: \
	}

2. * 构建文件对象:

 * 1)相对路径构建:File(String parent, String child) 

                             File(File parent, String child) 

 * 2)绝对路径构建:File(String pathname)

 * 分隔符的使用举例:

 * 1. "Android\\源代码\\2.jpg"  这里用双斜线是因为单斜线表示转义字符

 * 2. "Android"+File.separator+"源代码"+File.separator+"2.jpg"   适合动态生成的时候使用,优点是跨平台

 * 3.  "Android/源代码/2.jpg"  这是推荐方式。

 * 疑惑:windows下不是使用"\"为分隔符吗,为什么能使用其他平台下的"/"分隔符?

 * 解释:在windows下,用在java中相当于  \\==/。因此第一种和第三种写法是等效的。

public static void main(String[] args) {
		
		// 相对路径构建File对象
		String parentPath = "F:\\计算机技术\\Android\\源代码";
		String name = "2.jpg";// 2.jpg可以不存在,不报错。因为只是建立对象而已
		// File(String parent, String child)
		File file = new File(parentPath, name);
		System.out.println(file.getName());
		System.out.println(file.getAbsolutePath());
		//  File(File parent, String child)
		File file2 = new File(new File(parentPath), name);
		
		
		// 绝对路径构造File对象
		File file3 = new File("F:/计算机技术/Android/源代码");
		// 如果不写盘符地创建绝对路径File对象,是会在user.dir,即当前文件夹下创建。
		File file4 = new File("计算机技术"+File.separator+"Android"+File.separator+"源代码");
		System.out.println(file3.getParent());
		System.out.println(file3.getAbsolutePath());// Output:F:\计算机技术\Android\源代码
		System.out.println(file4.getAbsolutePath());
		// Output:F:\计算机技术\Android\Eclipse WorkPlace\IOProject\计算机技术\Android\源代码
	}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值