JAVA—IO—File

Java的IO包,五个类一个接口:

1.FILE(Java中文件和目录都当做文件看)

2.InputStream(字节流)

3.OutputStream

4.Reader(字符流)

5.Writer

Interface: Serializable


一.Class FILE:

1.常用构造方法:

File(File parent, String child)  //parent 抽象路径名和 child 路径名字符串

File(String pathname)  //通过将给定路径名字符串转换为抽象路径名来创建一个新 File

File(String parent, String child) //parent 路径名字符串和 child 路径名字符串

2.方法:

mkdir  //make directory 创建目录

createNewFile() //调用此方法可以创建一个文件 (要捕获一个IOException)

创建一个文件:haha.c到d盘下

CODE:

<pre name="code" class="java">import java.io.File;
import java.io.IOException;
public class FileDemo2 {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		File parent = new File("d:"+File.separator+"ook"+File.separator+"hehe");
		File child = new File(parent,"text.txt");
		File[] name = parent.listFiles();
		try{
			if(!parent.exists())			//判断是否有同名文件存在
			{	
				parent.mkdirs();			//可以一次创建多个目录 创建了ook和hehe两个文件夹	
			}
			else
			{
				System.out.println("该文件已经存在!!!");
			}
			if(parent.isDirectory())		//判断parent是不是一个目录
			{
				child.createNewFile();		//在父目录下创建一个文件
			}
			else
			{
				System.out.println("这不是一个目录,创建失败");
			}
		}catch(IOException ex)
		{
			ex.printStackTrace();
		}
		for(int i=0;i<name.length;i++)
			System.out.println(name[i]);
		System.out.println("文件的绝对路径:"+child.getAbsoluteFile());
		System.out.println("文件名:"+child.getName());
		System.out.println("文件父目录的路径:"+child.getParent());
		System.out.println("文件时候是文件:"+child.isFile());
		System.out.println("文件长度:"+child.length());
		System.out.println();
		for(int i=0;i<10;i++)
		{
			Thread.sleep(1000);        	//线程休眠1s
		}
		//删除文件
		child.delete();					//删除文件
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值