【问题标题】:Change the encoding of file using apache comons io doesn't work?使用 apache commons io 更改文件的编码不起作用?
【发布时间】:2017-05-02 13:16:10
【问题描述】:

我正在尝试使用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");

    }

下面是两张图,分别显示了源文件和目标文件的编码:

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

有什么想法吗?

【问题讨论】:

    标签: java notepad++ apache-commons-io


    【解决方案1】:

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

    您应该添加一些包含带有法语口音的单词的文本。然后在告诉 Notepad++ 将它们读取为 UTF-8 和 ANSI 后查看文件,并查看哪种编码导致文本可读。

    【讨论】:

    • 对不起加密字,只是打错了
    猜你喜欢
    • 2019-05-06
    • 1970-01-01
    • 2013-01-04
    • 2011-08-24
    • 2018-06-23
    • 2013-06-25
    • 2012-03-21
    • 2016-11-20
    • 1970-01-01
    相关资源
    最近更新 更多