Java-将文本文件中的单词读入数组时出现撇号错误 [英] Java - Apostrophe error when reading words from text file into an array

查看:46
本文介绍了Java-将文本文件中的单词读入数组时出现撇号错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下方法将.txt文件中的单词读入数组.

I am using the following method to read words in a .txt file into an array.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

public String[] readLines(String filename) throws IOException {
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    bufferedReader.close();
    return lines.toArray(new String[lines.size()]);
}
}

.txt文件中的第一个单词是不能".但是,当我调用此方法并在返回的数组中打印第一个单词时,我得到不能.数组中单词中的所有撇号都将替换为?.我该如何解决?

The first word in my .txt file is "can't". However when I call this method and print the first word in the returned array, i get can?t. All the apostrophes in the words in the array are being replaced by ?. How can I fix this??

推荐答案

您需要以特定的字符编码读取文件.您不能直接使用 FileReader 执行此操作.

You need to read your file in a specific character encoding. You cannot do this directly with FileReader.

相反,使用传递给 InputStreamReader FileInputStream 来指定字符集.在这种情况下,我们尝试使用 UTF-8 .

Instead use a FileInputStream passed to an InputStreamReader which specifies a charset. In this case, we try with UTF-8.

FileInputStream fileInputStream = new FileInputStream(filename);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");      
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
    lines.add(line);
}
bufferedReader.close();
System.out.println(lines.toArray(new String[lines.size()]));

这篇关于Java-将文本文件中的单词读入数组时出现撇号错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆