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



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

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

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

替换temp ==" harry" ...

相关内容

  • 没有找到相关文章

最新更新