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