黑马程序员技术交流社区
标题:
分享代码(将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt)
[打印本页]
作者:
小泽
时间:
2015-2-21 19:55
标题:
分享代码(将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt)
public class Test9 {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException,
IOException {
String sfile = "D:\\java";// 源文件路径
String dfolder = "D:\\txt";// 目的文件路径
File src = new File(sfile);
File des = new File(dfolder);
if (!des.exists()) { // 判断目的文件是否存在,不存在就创建
des.mkdirs();
}
File[] files = src.listFiles(); // 获取源文件夹中的文件。
for (File f : files) { // 遍历文件。
String str = f.getName();// 将文件中的Java文件名赋给str。
copyFile(sfile + "\\" + str, dfolder + "\\" + str);// 调用方法copyFile复制java文件并更改拓展名。
}
}
/**
* 使用字节流复制.java文件并把拓展名改为.txt。
*
* @throws FileNotFoundException
* @throws IOException
* @param str1 接收源文件地址。
* @param str2 接收目的文件地址。
*/
public static void copyFile(String str1, String str2)
throws FileNotFoundException, IOException {
StringBuilder sbl = new StringBuilder();// 创建一个容器,用来把源文件拓展名更改为.txt并转化成String。
sbl.append(str2);
sbl.replace(sbl.length() - 5, sbl.length(), ".txt");
String str = sbl.toString();
FileInputStream fis = new FileInputStream(str1);// 定义读取字节流。
BufferedInputStream bufis = new BufferedInputStream(fis);// 定义读取字节流缓冲区。
FileOutputStream fos = new FileOutputStream(str);// 定义写入字节流。
BufferedOutputStream bufos = new BufferedOutputStream(fos);// 定义写入字节流缓冲区。
int ch = 0;
while ((ch = bufis.read()) != -1) { // 一次读取并写入一个字节。
bufos.write(ch);
}
bufos.close();// 关闭流
bufis.close();// 关闭流
}
}
复制代码
欢迎大家指导。
作者:
小泽
时间:
2015-2-21 20:50
谢了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2