由于Java类包并没有提供太丰富的文件操作,平时很多实用的文件操作都只能由我们自己写代码实现。下面我们来实现一个在命令提示符窗口中使用文件拷贝的操作,即将给定目录内符合要求的文件(即特定后缀名)改为另一个给定的后缀名,并存入到给定的目录下。
实现原理其实也不难,在控制台输入四个参数,分别是“源目录、目标目录、源文件后缀名、目标文件后缀名”,然后遍历源目录下是否存在符合要求(即源文件后缀名)的文件,如果有,则修改后缀名并保存到目标目录中。
这里使用接口 FilenameFilter中的accept(File dir, String name)方法来实现,具体的使用方法请参看Java帮助文档。
具体代码实现如下:
- import java.io.File;
-
import java.io.FileInputStream;
-
import java.io.FileOutputStream;
-
import java.io.FilenameFilter;
-
import java.io.IOException;
-
-
public class Java2Jad {
-
-
-
private String sName;
-
private String tName;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public void java2jad(File sourceDir, File targetDir, String sourceName,
-
String targetName) throws IOException {
-
this.sName = sourceName;
-
this.tName = targetName;
-
-
File[] fileList = sourceDir.listFiles(new FilenameFilter() {
-
public boolean accept(File dir, String name) {
-
return (name.endsWith(Java2Jad.this.sName));
- }
- });
-
-
FileInputStream fis = null;
-
FileOutputStream fos = null;
-
File newFile = null;
-
for (File f : fileList) {
-
-
fis = new FileInputStream(f);
-
-
-
-
-
- String targetFileName = f.getName().replaceAll(
-
"\\" + sName + "$", tName);
-
newFile = new File(targetDir, targetFileName);
-
-
if(!newFile.exists()) {
- newFile.createNewFile();
- }
-
-
fos = new FileOutputStream(newFile);
-
-
- copyFile(fis, fos);
-
- fis.close();
- fos.close();
- }
- }
-
-
-
-
-
-
-
-
private void copyFile(FileInputStream fis, FileOutputStream fos) {
-
int temp = 0;
-
try {
-
while ((temp = fis.read()) != -1) {
- fos.write(temp);
- }
-
} catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
public static void main(String[] args) throws IOException {
-
if (args.length != 4) {
-
System.out.println("输入的参数个数不对!例如:Java2Jad F:\\source F:\\target txt jad");
-
System.exit(0);
- }
-
-
File sourceDir = new File(args[0]);
-
File targetDir = new File(args[1]);
-
-
String sourceName = "." + args[2];
-
String targetName = "." + args[3];
-
-
if (!sourceDir.exists()) {
-
System.out.println(sourceDir + " 源目录不存在!");
-
System.exit(0);
-
} else if (!sourceDir.isDirectory()) {
-
System.out.println(sourceDir + " 不是一个文件夹!");
-
System.exit(0);
- }
-
-
if (!targetDir.exists()) {
-
System.out.println("目标目录不存在!创建新目录!");
- targetDir.mkdir();
- }
-
-
new Java2Jad().java2jad(sourceDir, targetDir, sourceName, targetName);
-
System.out.println("文件改名并复制成功!");
- }
- }
源目录:
目标目录:
测试:
测试结果:
其实,在这个代码实现当中还有挺多不太合理、效率比较低之处,例如:复制操作中的读和写分别是直接使用了FileInputStream类中一次读一个字节的read()方法和FileOutputStream类中的write()方法,我们可以用带缓冲的高级一些的其他其他类来代替,这个在以后的文章中我再给出;另外,Java2Jad类中定义了两个String型实例变量,仅仅为了让下面的FilenameFilter匿名内部类中的accept()方法能访问而已,我个人觉得这样子处理不太好,希望各位能提出好建议互相学习。
本文转自 xxxx66yyyy 51CTO博客,原文链接:http://blog.51cto.com/haolloyin/335845,如需转载请自行联系原作者