本帖最后由 张涛的狂怒 于 2014-8-6 09:58 编辑
编写程序,将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt
我只把文件复制过去了,但是怎么改文件后缀?用rename吗?还是把文件名分解了?还有复制前改后缀方便还是复制后改后缀方便。
public class test9 {
public static void main(String args[]) throws Exception {
System.out.print("请输入源目录(所要复制的目录,格式如--c:\\java):");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
String fromPath = null;
// 源目录(所要复制的目录)
String toPath = null;
// 目标目录
fromPath = input.readLine();
System.out.println();
System.out.print("请输入目标目录(格式如--c:\\java):");
toPath = input.readLine();
test9.copyFiles(fromPath, toPath);
System.out.println();
input.readLine();
}
public static void copyFiles(String fromPath, String toPath)
throws Exception {
File fromFile = new File(fromPath);
if (fromFile.exists()) {
File toFile = new File(toPath);
if (toFile.exists()) {
System.out.println("目录" + toPath + "已经存在,复制文件操作失败!");
}else {
if (fromFile.isFile()) {
// 复制文件
File newToFile = new File(toPath);
newToFile.createNewFile();
FileInputStream inFile = new FileInputStream(fromFile);
FileOutputStream outFile = new FileOutputStream(newToFile);
FileChannel inChannel = inFile.getChannel();//得到对应的文件通道
FileChannel outChannel = outFile.getChannel();//得到对应的文件通道
long bytesWritten = 0;
long byteCount = inChannel.size();
while (bytesWritten < byteCount) {
//连接两个通道,并且从in通道读取,然后写入out通道
bytesWritten += inChannel.transferTo(bytesWritten,
byteCount - bytesWritten, outChannel);
}
System.out.println(fromFile.getName() + "已经成功为"
+ newToFile.getAbsolutePath() );
inFile.close();
outFile.close();
}
else { // 处理文件夹
if (toFile.mkdir()) { // 复制文件夹
System.out.println("目录" + toFile.getAbsolutePath()
+ "已经创建!");
File[] info = fromFile.listFiles();
for (int i = 0; i < info.length; i++) {
String toPathTemp = toPath + "\\"
+ info.getName();
copyFiles(info.getAbsolutePath(), toPathTemp);// 递归调用
}
}
else {
System.out.println("目录" + toFile.getAbsolutePath()
+ "创建失败!");
}
}
}
} else {
System.out.println("目录" + fromPath + "不存在,复制文件操作失败!");
}
}
}
|
|