因为Windows系统默认编码模式为gbk,而程序直接去读文件的话默认是utf-8模式,所以会出现乱码问题,所以在读文件的时候要指定编码格式。
解决方法:采用 java.io.FileInputStream 和 java.io.InputStreamReader
代码如下,读取txt文件,按行存入列表中,返回列表做后续分析。
public static List<String> readline(String filename)
{
File file = new File(filename);
InputStream in = null;
BufferedReader reader = null;
List<String> sentences = new LinkedList<>();
try{
//System.out.println("以行为单位读取文件内容,一次读一整行");
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gbk"));
String line = null;
while ((line = reader.readLine())!= null){
sentences.add(line);
}
reader.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (IOException el){
} } }
return sentences;
}
学习笔记:
1.FileInputStream :从文件系统的某个文件中获得输入字节,字节流。
2.FileReader :从文件系统的某个文件中获得输入字符,字符流,一个中文字是两个字节,一个字符。
3.FileInputStream 可以设置编码格式,FileReader 不可以。
4.InputStreamReader :从字节流到字符流的桥接器,它使用指定的字符集读取字节并将它们解码为字符。 它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。
5.BufferedReader :从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gbk"));
这一句就完成了读文件:字节——字符——文本的过程。