您的位置:首页 > 其它

含读写及替换字符的复制文件操作

2007-05-30 12:10 501 查看
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class ChangeFile {
/**
* 复制整个文件夹内容,并替换所有文件中的";"
*
* @param oldPath
* String 原文件路径 如:e:/b/
* @param newPath
* String 复制后路径 如:e:/a/
*/
public void copyFolder(String oldPath, String newPath) {

try {
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}

if (temp.isFile()) {

this.writeFile(this.readerFile(temp.toString()), newPath
+ "/" + (temp.getName()).toString());
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
System.out.println("复制文件夹操作 成功执行");
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();

}
}

public String readerFile(String filePath) {
String a = "";
File f = new File(filePath);
if (f.exists()) {
try {
// 下为读取文件
BufferedReader raf = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024 * 5];
int len = raf.read(buf);
a = new String(buf, 0, len);
} catch (Exception e) {
e.printStackTrace();
}
}
return a.replaceAll(";", " ");
}

public String readerFile(String filePath) {
StringBuffer sb = new StringBuffer();
File f = new File(filePath);
if (f.exists()) {
try {
// 下为读取文件
BufferedReader raf = new BufferedReader(
new FileReader(filePath));
String line = "";
while ((line = raf.readLine()) != null) {

if (line.trim().length() > 0) {

sb.append(line + "/r/n");
}
}
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
String b = sb.toString();
b = b.substring(0, b.length() - 2);
return b.replaceAll(";", " ");
}

public static void writeFile(String content, String filePath) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(filePath));
bw.write(content);
bw.flush();
} catch (Exception e) {
e.printStackTrace();

} finally {
if (bw != null) {
try {
bw.close();
} catch (Exception ex) {

}
bw = null;
}
}
}

public static void main(String[] args) {
ChangeFile a = new ChangeFile();
a.copyFolder("e:/b/", "e:/a/");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐