【问题标题】:Compare Strings read from txt file in java比较从java中的txt文件读取的字符串
【发布时间】:2015-12-31 10:49:17
【问题描述】:

我从 txt 文件中读取了一个字符串,我想将此字符串与我的参考进行比较。但它显示“不好”,我不知道为什么。

public class ReadFile {
    public static void main(String[] args) {
        try {
            File file = new File("nh.txt");
            FileReader fileReader = new FileReader(file);
            StringBuffer stringBuffer = new StringBuffer();
            int numCharsRead;
            //char[] charArray1 = new char[1024];
            char[] charArray = new char[1024];
            while ((numCharsRead = fileReader.read(charArray)) > 0) {
                stringBuffer.append(charArray, 0, numCharsRead);
            }



            String resultat = new String(charArray);
            String resultat1 = resultat.replaceAll("\\s", "");
            System.out.println(resultat1);
            String a="Nihao";
            if(a.equals(resultat1)){System.out.println("ok");}
            else System.out.println("not ok");


            fileReader.close();
            System.out.println("Contents of file:");
            System.out.println(stringBuffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

【问题讨论】:

  • 看不到你的输入文件,但也许你正在读回车?
  • resultat1 的值是多少?
  • 能否提供txt文件
  • @DeedarAliBrohi i hava Ni hao in my txt file
  • @npinti resultat1 的值为你好

标签: java string file compare


【解决方案1】:

这是因为字符串resultat1是一个1024个字符的长度,它的possible to a java string to have \0,它在内存中是这样的(如果文件包含Niaho):

Nihao\0\0\0..

因为\0 不是whitespace,所以这不会产生任何变化:

resultat.replaceAll("\\s", "");

所以你需要将这个字符 \0 替换为空:

resultat.replaceAll("\0", "");

或者简单地将引用字符串a 与stringBuffer.toString() 比较,即numCharsRead 长度:

if(a.equals(stringBuffer.toString())){System.out.println("ok");}
            else System.out.println("not ok");

【讨论】:

    猜你喜欢
    • 2017-08-20
    • 2015-05-09
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多