import java.io.File;
public class FileTest {
public static void main(String[] args) {
File files = new File("F:\\txt\\");
File file[] = files.listFiles();//获得目录中的文件及子目录信息
int i = (int) (Math.random()*file.length);
fun(file,i);
}
public static void fun(File file[],int i){
if(file[i].exists()){//如果文件存在
String name = file[i].getName();//获取文件名
if(file[i].isFile()&&name.endsWith(".txt")){ //如果是文件并且后缀名为.txt
File dest = new File("D:\\txt\\"+file[i].getName());
file[i].renameTo(dest);
}
else{
int j = (int) (Math.random()*file.length);
fun(file,j);
}
}else{
int j = (int) (Math.random()*file.length);
fun(file,j);
}
}
}
追问我想问一下复制过来的文件可以进行一下重命名吗?
追答可以的,File dest = new File("D:\\txt\\"+新文件名);
追问可以只是复制,而不是剪切吗?
追答加一个方法对文件进行读写操作。具体看代码
// 实现文件复制
public static void copyFile(File file1, File file2) {
try {
int byteread = 0;
if (file1.exists()) {// 如果文件存在
InputStream instream = new FileInputStream(file1); // 负责文件的读取
FileOutputStream fos = new FileOutputStream(file2); // 负责文件的写入
byte[] buffer = new byte[1024];
while ((byteread = instream.read(buffer)) != -1) {
fos.write(buffer, 0, byteread);
}
instream.close();
}
} catch (Exception e) {
System.out.println("复制文件操作出错!");
e.printStackTrace();
}
}
在上面的方法调用就行。具体就是把file[i].renameTo(dest);这句代码改成copyFile(file[i],dest);