第三节 文件操作 File类File类声明如下:public class File ectends Object implements Serializable,Comparable构造方法:public File(String pathname)public File(File patent,String chile)public File(String patent,String child)文件名的处理 String getName( ); //得到一个文件的名称(不包括路径) String getPath( ); //得到一个文件的路径名 String getAbsolutePath( );//得到一个文件的绝对路径名 String getParent( ); //得到一个文件的上一级目录名 String renameTo(File newName); //将当前文件名更名为给定文件的完整路径文件属性测试 boolean exists( ); //测试当前File对象所指示的文件是否存在 boolean canWrite( );//测试当前文件是否可写 boolean canRead( );//测试当前文件是否可读 boolean isFile( ); //测试当前文件是否是文件(不是目录) boolean isDirectory( ); //测试当前文件是否是目录普通文件信息和工具 long lastModified( );//得到文件最近一次修改的时间 long length( ); //得到文件的长度,以字节为单位 boolean delete( ); //删除当前文件目录操作 boolean mkdir( ); //根据当前对象生成一个由该对象指定的路径 String list( ); //列出当前目录下的文件例 8.4 自动更新文件。本例使用File类对象对指定文件进行自动更新的操作。程序如下:import java.io.*;import java.util.Date;import java.text.SimpleDateFormat;public class UpdateFile {public static void main(String args[]) throws IOException {String fname = "Write1.txt"; //待复制的文件名String childdir = "backup"; //子目录名new UpdateFile().update(fname,childdir);}public void update(String fname,String childdir) throws IOException {File f1,f2,child;f1 = new File(fname); //当前目录中创建文件对象f1child = new File(childdir); //当前目录中创建文件对象childif (f1.exists()) {if (!child.exists()) //child不存在时创建子目录child.mkdir();f2 = new File(child,fname); //在子目录child中创建文件f2if (!f2.exists() || //f2不存在时或存在但日期较早时f2.exists()&&(f1.lastModified() > f2.lastModified())) copy(f1,f2); //复制getinfo(f1);getinfo(child);}elseSystem.out.println(f1.getName()+" file not found!");}public void copy(File f1,File f2) throws IOException { //创建文件输入流对象FileInputStream rf = new FileInputStream(f1);FileOutputStream wf = new FileOutputStream(f2);//创建文件输出流对象int count,n=512;byte buffer[] = new byte[n];count = rf.read(buffer,0,n); //读取输入流while (count != -1){wf.write(buffer,0,count); //写入输出流count = rf.read(buffer,0,n);}System.out.println("CopyFile "+f2.getName()+" !");rf.close(); //关闭输入流wf.close(); //关闭输出流}public static void getinfo(File f1) throws IOException {SimpleDateFormat sdf;sdf= new SimpleDateFormat("yyyy年MM月dd日hh时mm分");if (f1.isFile())System.out.println("<FILE>\t"+f1.getAbsolutePath()+"\t"+f1.length()+"\t"+sdf.format(new Date(f1.lastModified())));else{System.out.println("
相关资源:敏捷开发V1.0.pptx