java遍历转换项目的编码格式
非c盘保护盘下
public class ReadFile {
private InputStreamReader isr = null;
private OutputStreamWriter osw = null;
private FileInputStream fis = null;
private FileOutputStream fos = null;
public ReadFile() {
}
public void getAllFiles(String path) {
File file = new File(path);
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
getAllFiles(f.getPath());
} else {
//对文件进行过滤
if (f.getPath().endsWith(".txt")) {
//在这里面进行代码的转换
System.out.println(f);
changeCodeEcoding(f.getPath());
}else{
//不进行转换直接复制
System.out.println(f.getPath());
copyFile(f.getPath());
}
}
}
}
//复制非后缀名的文件
private void copyFile(String path) {
try{
fis = new FileInputStream(path);
String s = changePath(path);
File file = new File(s);
if(!file.exists()){
file.getParentFile().mkdirs();
fos = new FileOutputStream(s);
}
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//对文件进行编码转化
public void changeCodeEcoding(String path) {
try {
isr = new InputStreamReader(new FileInputStream(path), "gbk");
String s = changePath(path);
File file = new File(s);
if(!file.exists()){
file.getParentFile().mkdirs();
osw = new OutputStreamWriter(new FileOutputStream(s), "utf-8");
}
char[] c = new char[1024];
int len = 0;
while ((len = isr.read(c)) != -1) {
osw.write(c, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
isr.close();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//将a项目copy转换编码到同路径的aa文件夹下
public String changePath(String path) {
String newPath = path.replace("\\a\\", "\\aa\\");
return newPath;
}
public static void main(String[] args) {
ReadFile rf = new ReadFile();
//文件所在的路径
rf.getAllFiles("d:\\desktop\\a");
}
}