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(); //删除文件
}
}