在Java中从UTF8转换为ASCII

时间:2017-11-17 23:05:58

标签: java utf-8 ascii

我编写了一个代码来读取文本文件中的数据。我想知道在从文件加载数据后如何从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;
}

1 个答案:

答案 0 :(得分:0)

这是您的原始代码:

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);
        }
    }