首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用Java实现UTF8到ASCII码的转换

用Java实现UTF8到ASCII码的转换
EN

Stack Overflow用户
提问于 2017-11-18 07:05:58
回答 1查看 2K关注 0票数 1

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

代码语言:javascript
运行
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2017-11-18 07:26:34

这是你的原始代码:

代码语言:javascript
运行
复制
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;
}

将其更改为:

代码语言:javascript
运行
复制
public static List<String> readFile(String filename) throws Exception {
   return Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
}

记住导入相关的java.nio包,否则你的程序会给你一个编译错误。

下面是一个完整的工作程序:

代码语言:javascript
运行
复制
    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);
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47360576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档