文件夹的读写是很好的一个Java I/O操作的典型案例,涉及到I/O流的操作、递归调用、循环。用程序修改文件名、复制拷贝文件本文都有可参考价值。通过编写此程序也将对递归思想有更好的理解。
本程序也加了一个定时器,可1秒执行一次复制操作,写定时任务也是经常会用到的。定时对文件夹的备份,就不用我们自己再去执行备份工作了。重复的工作都可交给机器来做。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class Copy
{
public static void copyFile(String oldPath, String newPath)
throws Exception
{
File createFile = new File(newPath);
if (!createFile.exists())
{
createFile.createNewFile();
}
FileInputStream is = new FileInputStream(oldPath);
BufferedInputStream bs = new BufferedInputStream(is);
FileOutputStream os = new FileOutputStream(newPath);
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int length = 0;
while (-1 != (length = bs.read(buffer, 0, 1024)))
{
// String str = new String(buffer, 0, length);
// bos.write(str.getBytes());
bos.write(buffer, 0 , length);
}
bos.flush();
bos.close();
bs.close();
}
public static void copyDirectory2(String oldPath, String newPath)
throws Exception
{
File createFile = new File(newPath);
createFile.mkdirs();
File file = new File(oldPath);
File[] f = file.listFiles();
for (int i = 0; i < f.length; i++)
{
if (f[i].isDirectory())
{
String dir1 = oldPath + "/" + f[i].getName();
String dir2 = newPath + "/" + f[i].getName();
copyDirectory2(dir1, dir2);
}
if (f[i].isFile())
{
copyFile(oldPath + "/" + f[i].getName(), newPath + "/" + f[i].getName());
}
}
}
public static void main(String[] args)
{
Calendar second = Calendar.getInstance();
second.setTimeInMillis(1000);
Timer t = new Timer();
t.schedule(new TimerTask()
{
@Override
public void run()
{
String oldPath = "e:/书";
String newPath = "e:/书2";
try
{
File file = new File(oldPath);
if (file.isDirectory())
{
copyDirectory2(oldPath, newPath);
}
else
copyFile(oldPath, newPath);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}, 0,second.getTimeInMillis());
}
}