2

解决eclipse中的Java文件,使用idea打开的乱码问题 - 2337

 2 years ago
source link: https://www.cnblogs.com/cjin-01/p/16632660.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
2884444-20220828140126796-1102314735.png
2884444-20220828140140907-21326155.png

在克隆一些Github上面资源的时候,使用idea打开,会出现乱码的情况😖

而使用eclipse打开,这种情况就会消失。「是因为eclipse使用的是GBK编码,idea使用的是utf-8」

这种情况困扰了我好几次,我也试过各种软件再转码,但是没丁儿用!

终于,今天又碰到了;

是可忍,孰不可忍!

于是自己写了一个Java类,专门用来将GBK编码的Java文件,转换成utf-8编码✌️

ps:改一改,可以将utf-8,转换成GBK

技术点:递归,IO流

以下是代码,如果是mac操作系统,以下代码应该不会有什么问题;

1、如果是window系统,文件路径/需要转换成\ (好像是的吧?)

2、强烈建议不要进行二次转换,更不要进行多次转换!!!

3、最好将需要转换的文件夹/文件复制一份,以免出现编码转换的意外

4、没了,以下代码有注释

package com.project_generator.eclipseConvert;

import org.junit.Test;

import java.io.*;
import java.util.List;

/**
* 建议:最好将需要转换的文件夹/文件复制一份,以免出现编码转换的意外
* 注意:不要进行二次转换,还有一定要确定被转换的文件是GBK格式的【一般,如果eclipse的文件放到idea中乱码,多半是GBK格式的】
*/
public class Converter {
// 复制完全一样的文件,包含文件夹里面的所有内容【略--手动处理】

public static void main(String[] args) throws IOException {
new Converter().converter(new File("这里填写自己文件夹or文件的绝对路径"));
    }

@Test
public void converter(File file) throws IOException {
convertEclipseFiles(file); // 【必改,文件的路径】
System.out.println("转换成功!");
}

public void convertEclipseFiles(File file) throws IOException {
if (!file.exists()) {
throw new RuntimeException("此文件或文件夹不存在");
}
if (file.isFile() && file.getName().endsWith(".java")) { //【可改,将eclipse里面的Java文件编码改成utf-8】
//!! 重写文件,最后删除原来的文件
String absolutePath = file.getAbsolutePath();
File file1 = new File(absolutePath.substring(0, absolutePath.length() - 5) + "_copy" + ".java");
convertEncoding(file,file1);
file.delete();
file1.renameTo(new File(absolutePath));
}
if (!file.isFile()) {
File[] fs = file.listFiles();// 获取当前文件夹下的子文件夹或者文件的file对象
if (fs != null && fs.length > 0) {
for (File ff : fs) {
convertEclipseFiles(ff);// 递归
}
}
}
}

/*
* 目标:把1.txt内容复制到2.txt
*/
public void convertEncoding(File oldFile, File newFile) throws IOException {
FileInputStream fis = new FileInputStream(oldFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] content = new byte[1024];
int read = fis.read(content);
while (read != -1) {
// System.out.println(new String(content, 0, read, "GBK")); // 查看read的结果
fos.write(new String(content, 0, read, "GBK").getBytes("utf-8"));
read = fis.read(content);
}
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK