代码文件切换编码

发布时间:2024-03-07 16:48:58

蝴蝶项管有一些旧代码不知道什么情况,采用的了gb18030,导入工作空间后注释显示的全是乱码。就需要转码 如果需要获取原来编码可以使用hbuildx

package com.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;

public class ChangeCode {
	public static void main(String[] args) {
		changeCode("/Users/gujun/schoolspace/jsp_001_score/src");
	}
	
	private static String readFile(String filePath) throws IOException {
		File file = new File(filePath);
		FileReader fr = new FileReader(file, Charset.forName("gb18030"));
		BufferedReader br = new BufferedReader(fr);
		StringBuffer filecontent=new StringBuffer();
		String line;
		while((line = br.readLine()) != null){
		    // 一行一行地处理...
		    System.out.println(line);
		    filecontent.append(line).append("\n");
		}
		return filecontent.toString();
	}
	
	public static void writeFileToLoaction(String content,String filePath) {
        try {
            File f = new File(filePath);
            if(!f.exists())
                f.createNewFile();
            FileWriter fw = new FileWriter(f.getAbsoluteFile(),false);//追加
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	public static void changeCode(String dirPath) {
		try {
			File dir=new File(dirPath);
			for (File subFile : dir.listFiles()) {
				if(subFile.isDirectory()) {
					changeCode(subFile.getAbsolutePath());
				}else {
					if("java".equals(getExtension(subFile.getName()))) {
						System.out.println(subFile.getAbsolutePath());
						String fileContent=readFile(subFile.getAbsolutePath());
						System.out.println(fileContent);
						writeFileToLoaction(fileContent,subFile.getAbsolutePath());
					}
					

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	public static String getExtension(String fileName) {
	    char ch;
	    int len;
	    if(fileName==null || 
	            (len = fileName.length())==0 || 
	            (ch = fileName.charAt(len-1))=='/' || ch=='\\' || //in the case of a directory
	             ch=='.' ) //in the case of . or ..
	        return "";
	    int dotInd = fileName.lastIndexOf('.'),
	        sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
	    if( dotInd<=sepInd )
	        return "";
	    else
	        return fileName.substring(dotInd+1).toLowerCase();
	}
	
}


Card image cap
APP STORE
Card image cap
应用宝
Card image cap
小米
Card image cap
华为