文件的更新
import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;
public class FileUpdateTest {
public static void main(String[] args) throws IOException{
String fname="source.txt";
String destdir="backup";
update(fname,destdir);
}
public static void update(String fname,String destdir) throws IOException{
File f1,f2,dest;
f1=new File(fname);
dest=new File(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()+"文件不存在");
}
}
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[n];
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) throws IOException{
SimpleDateFormat sdf;
sdf=new SimpleDateFormat("yyyy年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]);
}
}
}
}
import java.util.Date;
import java.text.SimpleDateFormat;
public class FileUpdateTest {
public static void main(String[] args) throws IOException{
String fname="source.txt";
String destdir="backup";
update(fname,destdir);
}
public static void update(String fname,String destdir) throws IOException{
File f1,f2,dest;
f1=new File(fname);
dest=new File(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()+"文件不存在");
}
}
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[n];
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) throws IOException{
SimpleDateFormat sdf;
sdf=new SimpleDateFormat("yyyy年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]);
}
}
}
}