Java IO之File类学习

 

File:An abstract representation of file and directory pathnames. 文件和文件夹路径名的抽象表示

(1)创建文件

例:在指定目录下,创建一个文件(File):

	public static void main(String[] args)
	{
//		File file = new File("E:/sailang/lizhongyi.doc");
		
//		File file = new File("E:/sailang");
//		File file2 = new File(file, "lizhongyi.txt");
		
		File file = new File("E:/sailang", "lizhongyi.doc");
		
		try
		{
			System.out.println(file.createNewFile());
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

creatNewFile() 只能创建文件,需要注意的是,在创建文件时,文件所在目录结构必须已经存在,否则会报错!

补充:

在windows操作系统中,目录结构为:E:\sailang。其中使用的反斜杠\,但是在Java中,\是被用作转意字符的, 因此,这种目录结构不能够直接作为File()的参数,有两种解决方法:

  • E:\\sailang
  • E:/sailang     这种方法在多数操作系统中都适应,因此,一般选用这种!

(2)创建目录

File file = new File("E:/sailang/lizhongyi");
		
file.mkdir();

采用mkdir方法创建lizhongyi子目录时,其前面的目录必须都已经存在!

而mkdirs() 可以把所有的子目录都可以创建出来!

 

isFile:Tests whether the file denoted by this abstract pathname is a normal file.

isDirectory:Tests whether the file denoted by this abstract pathname is a directory.

mkdir:Creates the directory named by this abstract pathname.

mkdirs:Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

 

(3)返回指定目录下所包含的文件或者子目录的名字

 list:Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

		File file = new File("E:/sailang");
		
		if(file.mkdirs() == false)
		{
			String[] names = file.list();
			
			for(String name : names)
			{
				System.out.println(name);
			}			
		}



(4)FilenameFilter

这个类在《设计模式之策略模式》中有,是最后一个例子,大家想看的可以看看!

 

(5)以树形结构展现目录以及其内部的文件

代码参见《如何编写递归程序

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值