java - 使用 apache commons io 更改文件的编码不起作用?

标签 java notepad++ apache-commons-io

我尝试使用 FileUtils 更改 txt 文件的编码,但在执行该函数后,我使用 NotePad++ 检查文件的编码,但编码没有变化文件的内容。

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;


 public class FileManager {


     public void changeFileCharset(File file) throws IOException{

            String content = FileUtils.readFileToString(file, "ISO-8859-1");
            FileUtils.write(file, content, "UTF-8");

    }

        public static void main(String[] args) throws IOException {
            FileManager fileManager = new FileManager();
            fileManager.changeFileCharset(new File("unknown_words.txt"));
        }

}

我还使用 BufferedReaderBufferedWriter 尝试了此功能,但我什么也没得到。

 public static void transform(File source, String srcEncoding, File target, String tgtEncoding) throws IOException {
        try (
          BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source), srcEncoding));
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding)); ) {
              char[] buffer = new char[16384];
              int read;
              while ((read = br.read(buffer)) != -1)
                  bw.write(buffer, 0, read);
        } 
    }

 public static void main(String[] args) throws IOException {

     FileManager manager = new FileManager();
     File file = new File("test.txt");
     File file1 = new File("test1.txt");
     manager.transform(file, "UTF-8", file1, "ISO-8859-1");

    }

下面两张图片显示了源文件和目标文件的编码:

enter image description here enter image description here

是NotePad++的字符集检查方法不好还是什么?

有什么想法吗?

最佳答案

编码不是“加密”(如您所说)。此外,Notepad++ 确定文件使用的编码并不总是那么容易。例如,如果所有内容都是纯ASCII字符,那么UTF-8和ISO-8859-1编码的文件没有区别。

您应该添加一些包含带有法语口音的单词的文本。然后在告诉 Notepad++ 以 UTF-8 和 ANSI 格式读取文件后查看文件,看看哪种编码会产生可读的文本。

关于java - 使用 apache commons io 更改文件的编码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43738910/

相关文章:

java.util.zip.ZipException : invalid stored block lengths

java - 从静态上下文访问非静态方法

Java 部署工具包 - 何时内联安装?

java - java中的对象头和填充是什么

xsd - 在XML模式中定义maxLength构面的语法是什么?

regex - 是否可以替换正则表达式序列中的特定字符?

android - 错误 "java.lang.NoClassDefFoundError: com.google.repacked.apache.commons.io.FileUtils"

java - 如何使用 commons.io.FileUtils 读/写 docx 文件?

java - 如何使用spring boot读取jsp文件?

editor - 在 TortoiseHg 中使用其他编辑器