12.1 操作文件的类File
io包中与文件本身有关的类就是File类。
//该类的构造方法如下 参数需要给定文件路径public File(String pathname){}//File类定义了若干方法 和常量public static final String pathSeparator //常量 表示路径的分隔符(windows是: “;”)public static final String separator //常量 路径分隔符(windows是:“\”) Linux是“/”public boolean createNewFile() throws IOException //普通 创建文件public boolean delete() //删除文件public boolean exists() //判断文件是否存在public boolean isDirectory() //判断给定的路径是否是一个目录public long length() //返回文件的大小public String[] list() //列出指定目录的全部内容,只是列出列名称public File[] listFiles() //列出指定目录的全部内容,会列出路径public boolean mkdir() //创建一个目录public boolean renameTo(File dest) //为已有的文件重新命名
12.1.3 范例:列出指定目录的全部内容
1.需求:给定一个目录,列出目录下的全部内容,给定的目录可能存在子文件夹,要求可以把所有的子文件夹的子文件列出来。
public static void main(String args[]){ File f =new File("d:"+File.separator); //操作路径 print(f) ; }public static void print(File f){ //调用递归方法 if(f !=null){ if(f.isDirectory()){ //是否是目录 File file[] =f.listFiles(); //是列出 if(file !=null){ for(int i=0;i< file.length;i++){ print(file[i]); } } } else{ //否 直接打印 System.out.println(f); } } }
12.2RandomAccessFile类 (进行文件内容的操作)
public RandomAccessFile(File file,String mode) throws FileNotFoundException //构造 接受File类的对象,指定操作路径,但是在设置时需要设置模式,r为只读;w为只写;rw为读写;public RandomAccessFile(String name,String mode) throws FileNotFoundException //构造 不再使用File类对象表示文件,而是直接输入了一个固定的文件路径public void close() throws IOException //关闭操作public int read( byte[] b) throws IOEception //将内容读取到一个byte数组中public final byte readByte() throws IOEception //读取一个字节public final int readInt() throws IOEception //从文件中读取整型数据public void seek(long pos) throws IOEception //设置度指针的位置public final void writeByte(String s) throws IOEcetion //将一个字符串写入到文件中,按字节的方式处理public final void writeInt(int v) throws IOEception //将一个int型数据写入文件,长度为4位public int skipByte(int n) throws IOEception //指针跳过指定字节
如果要写入的文件不存在,系统将自动进行创建