这是你的原代码:
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);
}
}
UTF8到ASCII转换没有很好地定义为UTF-8有很多比ASCII多个字符。在您的转换中,如果遇到不是ascii字符的UTF8字符,您希望做什么? – vandale
您是指基本ASCII字符集还是其中一个*增强型* ASCII字符集?如果只是基数,并且您的数据*可以存储在基本ASCII中,则不需要转换,因为Unicode包含所有具有相同码点值的基本ASCII字符。 – Andreas
是的基本字符集,但在我原来的文件中,我有这样的字符:Šaltenis,Simonas –