------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
/*
* 第九题:编写程序,将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt
* 晕了
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class text9 {
public static File file;
public static File file1;
public static void main(String[] args) {
file = new File("D:\\毕向东java预热");
file1 = new File("D:\\text");
File ff = splittxt1(file,file1);
if(ff == null ){
return ;
}else{
Copy(file, ff);
}
}
public static void Copy(File file,File file1){
FileInputStream fps = null;
FileOutputStream fos = null;
String temp = null;
File fff = null;
if(file.exists()){
File[] s = file.listFiles();
File[] ss = file1.listFiles();
for(int x = 0; x< s.length; x++){
fps = new FileInputStream(s[x]);
fos = new FileOutputStream(ss[x]);
byte[] by = new byte[1024];
int len = 0;
try {
while((len = fps.read(by)) != -1){
fos.write(by, 0, len);
}
fos.flush();
fos.close();
fps.close();
}
}
//修改后缀名与存入另一个文件夹
public static File splittxt1(File file11,File file1){
//文件路径名数组
File[] sc = file1.listFiles();
//字符串文件路径名数组
String[] ss = file11.list();
//后缀名
String tep = ".txt";
String[] sp = null;
File sr = null;
for(int i=0; i<ss.length;i++){
if(sc[i].exists()){
System.out.println("文件已存在");
return null;
}
//字符串数组路径名切割
sp = ss[i].split("\\.");
//合并成新的路径名并存入指定文件夹
sr = file11.createTempFile(sp[0], tep, file1);
return file1;
}
}
<br/>
对于文件的重命名其实有更好的方法
通过String类中的String.endsWith(String suffix)找到后缀名为".java"的文件
然后replace(char oldChar, char newChar)方法就可以直接替换成
replace(".java", ".txt")
而不必进行文件的切割与合并
public static File splittxt1(File file11,File file1)
String
类中endsWith(String suffix)找到指定的后缀字符,startsWith
(String prefix)找到指定的后缀字符,contains(CharSequence s)找到指定的中间字符。然后可以通过replace(),replaceAll()方法尽心字符串的修改
代码:
public class text9 {
public static void main(String[] args) throws IOException {
File source = new File("D:\\ecppack\\exam\\src\\com\\itheima");
File target = new File("D:\\text");
fileCheck(source,target);
}
public static void fileCheck(File source,File target) throws IOException{
File[] files = source.listFiles();
for(File file : files){
if(file.isFile()){
if(file.getName().endsWith(".java"))
fileCopy(file,target);
}else{
fileCheck(source,target);
}
}
}
public static void fileCopy(File source,File target) throws IOException{
String Name=source.getName().replace(".java", ".txt");
File newTarget=new File(target,Name);
BufferedInputStream bfis = new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream bfos = new BufferedOutputStream(new FileOutputStream(newTarget));
int len = 0;
while((len=bfis.read())!=-1){
bfos.write(len);
}
bfis.close();
bfos.close();
}
}
------- <a href="http://www.itheima.com" target="blank">Windows Phone 7手机开发</a>、<a href="http://www.itheima.com" target="blank">.Net培训</a>、期待与您交流! -------