自动创建文件夹,文件转移,基本上系每个项目都需要遇到的工作。
(1)在Java中,可以使用mkdirs()方法实现。mkdirs()对比起mkdir()方法更为好用,因为其能创建包括所有必须但不存在的父目录,该方法隶属于File类。代码举例:
public static boolean createDir(String destDirName){
File dir = new File(destDirName);
if(dir.exists()){
return false;
}else{
dir.mkdirs();
return true;
}
}
该方法使用简单,但功能较为强大。当然,如果在项目开发中忘记了创建文件夹,又不想改程序,亦可以通过bat批处理辅助完成该任务。
(2)在Java中,文件的移动需要使用到File类中的renameTo()方法。
public static void fileMove(File file, String toFolder){
if(file.exists() == false){
System.out.println("The source file(" + file.getAbsoluteFile() + ") can not be found!");
return;
}
File newFolder = new File(toFolder);
if(newFolder.exists() == false){
newFolder.mkdirs();
}
File moveFile = new File(newFolder.getPath() + "\\" + file.getName());
if(moveFile.exists()){
String strNewFileName = newFolder.getPath() + "\\" + file.getName() + "_" + new Date().getTime();
System.out.println("File:" + moveFile.getName() + " is exist, File will be change by this name:" + strNewFileName);
moveFile = new File(strNewFileName);
}
file.renameTo(moveFile);
}
在main方法中使用类似 fileMove(new File("c:\\aaa.txt"), "D:");语句,文件file会直接转移到新的文件夹toFolder中。
补充:面向对象的特性之一,就是方法的重载,我以转移文件的方法为例:多写一个方法:
public static void fileMove(String fileName, String toFolder){
fileMove(new File(fileName), toFolder);
}
则再main方法中,使用任何一句语句都可以执行成功:
fileMove("c:\\aaa.txt", "D:"); 或者 fileMove(new File("c:\\aaa.txt"), "D:");
该例子亦系对重载,非常好的一个描述。
(1)在Java中,可以使用mkdirs()方法实现。mkdirs()对比起mkdir()方法更为好用,因为其能创建包括所有必须但不存在的父目录,该方法隶属于File类。代码举例:
public static boolean createDir(String destDirName){
File dir = new File(destDirName);
if(dir.exists()){
return false;
}else{
dir.mkdirs();
return true;
}
}
该方法使用简单,但功能较为强大。当然,如果在项目开发中忘记了创建文件夹,又不想改程序,亦可以通过bat批处理辅助完成该任务。
(2)在Java中,文件的移动需要使用到File类中的renameTo()方法。
public static void fileMove(File file, String toFolder){
if(file.exists() == false){
System.out.println("The source file(" + file.getAbsoluteFile() + ") can not be found!");
return;
}
File newFolder = new File(toFolder);
if(newFolder.exists() == false){
newFolder.mkdirs();
}
File moveFile = new File(newFolder.getPath() + "\\" + file.getName());
if(moveFile.exists()){
String strNewFileName = newFolder.getPath() + "\\" + file.getName() + "_" + new Date().getTime();
System.out.println("File:" + moveFile.getName() + " is exist, File will be change by this name:" + strNewFileName);
moveFile = new File(strNewFileName);
}
file.renameTo(moveFile);
}
在main方法中使用类似 fileMove(new File("c:\\aaa.txt"), "D:");语句,文件file会直接转移到新的文件夹toFolder中。
补充:面向对象的特性之一,就是方法的重载,我以转移文件的方法为例:多写一个方法:
public static void fileMove(String fileName, String toFolder){
fileMove(new File(fileName), toFolder);
}
则再main方法中,使用任何一句语句都可以执行成功:
fileMove("c:\\aaa.txt", "D:"); 或者 fileMove(new File("c:\\aaa.txt"), "D:");
该例子亦系对重载,非常好的一个描述。