【问题标题】:Converting from UTF8 To ASCII in Java在 Java 中从 UTF8 转换为 ASCII
【发布时间】:2018-05-01 19:35:45
【问题描述】:

我编写了一个从文本文件中读取数据的代码。我想知道从文件加载数据后如何从 UTF8 转换为 ASCII。以下是我编写的部分代码,但需要找到进行转换的方法。正如我在之前的问题中所说,我对 Java 很陌生,请帮帮我。

public static List<String> readFile(String filename) throws Exception {
    String line = null;
    List<String> records = new ArrayList<String>();


    BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));



    while ((line = bufferedReader.readLine()) != null) {
        records.add(line.trim());
    }


    bufferedReader.close();
    return records;
}

【问题讨论】:

  • UTF8 到 ascii 的转换没有很好的定义,因为 utf8 的字符比 ascii 多得多。在你的转换中,如果遇到非ascii字符的UTF8字符,你想怎么办?
  • 您指的是基本 ASCII 字符集,还是众多 增强 ASCII 字符集之一?如果只是基础,并且您的数据可以存储在基础 ASCII 中,则不需要转换,因为 Unicode 包含具有相同代码点值的所有基础 ASCII 字符。
  • 是的基本字符集,但在我的原始文件中,我有这样的字符:Šaltenis, Simonas
  • 您的代码使用用户的默认字符编码(谁知道)读取并存储为 Java 字符串(即 UTF-16)。您为什么要询问 ASCII 以及它会在您的程序中出现的位置?
  • 您检查过我在链接中的代码吗?我有一个复杂的文本文件,我只想提高插值搜索性能

标签: java utf-8 ascii


【解决方案1】:

这是您的原始代码:

public static List<String> readFile(String filename) throws Exception {
String line = null;
List<String> records = new ArrayList<String>();


BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));



while ((line = bufferedReader.readLine()) != null) {
    records.add(line.trim());
}


bufferedReader.close();
return records;
}

改成:

public static List<String> readFile(String filename) throws Exception {
   return Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
}

记得导入相关的java.nio包,不然你的程序会报编译错误。

这是一个完整的程序:



    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.List;

    public class Tests {
        public static void main(String[] args) {
            String filename = "C:\\Users\\username\\Desktop\\test.txt";
            try {
                for(String s : readFile(filename)) {
                    System.out.println(s);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public static List readFile(String filename) throws Exception {
            return Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
        }
    }

【讨论】:

  • 我需要导入任何实用程序吗?我收到一条消息:找不到符号 - 变量路径
  • @CosaRamirez 它位于此处:java.nio.file.Paths。所以继续将 java.nio* 和 java.nio.file* 导入到你的类的开头
  • 好的,我这样做了,现在我得到以下信息:找不到符号变量 StandardCharsets
  • @CosaRamirez 也导入 java.nio.charset.*
  • 你能告诉我在while循环和方法结束时要做什么
猜你喜欢
  • 2011-05-20
  • 1970-01-01
  • 2015-06-04
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
  • 2017-03-30
相关资源
最近更新 更多