您的位置:首页 > 其它

利用File自动更新文件

2011-08-31 07:37 323 查看
File类提供了一些方法可以用来操作文件和获得文件的信息.通过File类的方法,可以得到文件或目录的描述,包括名称,所在路径,读写性,长度等,静儿可以进行创建目录,创建临时文件,改变文件名,删除文件,列出一个目录中所有的文件或某个模式相匹配的稳健操作等...

1.构造方法

public File(String pathname):根据parent抽象路径名和child路径名字符串创建一个新File对象.

public File(File parent,String child):通过将制定路径名字符串和child路径名字符串创建一个新File对象.

public File(String parent,String child):根据parent路径名字符串和child路径名字符串创建一个新File对象.

public File(URI uri):通过将指定的File:URI转化为一个抽象路径名来创建一个新的File对象.

2.提供的方法

(1)访问文件对象

public String getName():返回文件对象名,不包括路径名

public String getPath():返回相对路径名,包含文件名

public String getAbsolutePath():返回绝对路径名,包含文件名

public String getParent():返回父文件对象的路径名

public File getParentFile():返回父文件对象

(2)获得文件属性

public long length();返回指定文件的字节长度

public boolean exists():测试指定的文件是否存在

public long lastModified()返回指定文件最后被修改的时间.

(3)文件操作

public boolean renameTo(Filedest)文件重命名

public boolean delete()删除空目录

(4)目录操作

public boolean mkdir():创建指定目录,正常建立时返回true

public String[] list():返回目录中的所有文件名字符串

public File[] listFiles():返回指定目录中的所有文件对象

实例:

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.Date;

public class FileUpdateTest {

public static void main(String[] args) throws IOException{

String fname = "source.txt";

String destdir = "backup";

update(fname,destdir);

}

private static void update(String fname, String destdir) throws IOException {

File f1,f2,dest;

f1=new File("res",fname);

dest = new File("res",destdir);

if(f1.exists()){

if(!dest.exists())

dest.mkdir();

f2 = new File(dest,fname);

long d1 = f1.lastModified();

long d2 = f2.lastModified();

if((!f2.exists()) || f2.exists() && d1>d2){

copy(f1,f2);

}

showFileInfo(f1);

showFileInfo(dest);

}else{

System.out.println(f1.getName()+"file not found");

}

}

public static void copy(File f1, File f2) throws IOException{

FileInputStream fis = new FileInputStream(f1);

FileOutputStream fos = new FileOutputStream(f2);

int count,n = 512;

byte buffer[] = new byte
;

count = fis.read(buffer,0,n);

while(count!=-1){

fos.write(buffer,0,count);

count = fis.read(buffer,0,n);

}

System.out.println("复制文件"+f2.getName()+"成功");

fis.close();

fos.close();

}

public static void showFileInfo(File f1) {

// TODO Auto-generated method stub

SimpleDateFormat sdf;

sdf = new SimpleDateFormat("yyy 年 MM 月 dd 日 hh 时 mm 分");

if(f1.isFile()){

String filepath = f1.getAbsolutePath();

Date da = new Date(f1.lastModified());

String mat = sdf.format(da);

System.out.println("<文件:>\t"+filepath+"\t"+f1.length()+"\t"+mat);

}

else{

System.out.println("<目录:>\t"+f1.getAbsolutePath());

File[]files = f1.listFiles();

for(int i=0;i<files.length;i++){

showFileInfo(files[i]);

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: