从文件输入字符串并比较输入字符串

时间:2017-09-23 12:11:38

标签: java character-encoding datainputstream ioutils

我想从文件中输入字符串并检查每个字符串是否与给定字符串匹配,但我无法做到。在此先感谢您的帮助。 我的代码如下:

import java.util.*;
import java.io.*;
import org.apache.commons.io.*;
import java.nio.charset.*;

public class XYZ
{
    String s[] = {"Harry","Potter","Pirates","Of","The","Carribean"};

    XYZ()
    {
        save();
        String []copyString = load();
        for(int i=0; i<6; i++)
        {
            System.out.print("String " + i + ": " + copyString[i]);
        }
    }

这是我的save()函数,用于将字符串保存到文件中:

public void save()
{
    DataOutputStream output = null;
    try
    {
        output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("the-file-name.txt"))); 
        for(int i=0; i<6; i++)
        {
            output.writeUTF(s[i]);
        }
        output.close();
    }
    catch(IOException e){}      

}

这是我的load()函数,它返回一个字符串:

    public String[] load()
    {
        final Charset UTF_8 = Charset.forName("UTF-8");     
        String temp;
        String copyFromFile[] = new String[6];

        DataInputStream input = null;
        try
        {
            input = new DataInputStream(new BufferedInputStream(new FileInputStream("the-file-name.txt")));
            for(int i=0; i<6; i++)
            {

                temp = input.readUTF(); 
                if(temp == "Harry" || temp == "Potter"  || temp == "Pirates"  || temp == "Of"  || temp == "The"  || temp == "Carribean" )
                {
                    copyFromFile[i] = temp;
                }
                else
                {
                    System.out.println("Not matched");
                }
            }
            input.close();
        }catch (IOException e){}
        return copyFromFile;
    }

最后,我的main()功能:

public static void main(String[]arg)
{
    XYZ xyz = new XYZ();

}

}

输出:

Not matched
Not matched
Not matched
Not matched
Not matched
Not matched

1 个答案:

答案 0 :(得分:0)

使用.equals进行字符串比较。 你应该用temp.equals()

替换temp ==“Harry”...