Введите строку из файла и сравните входную строку

Я хочу ввести строки из файла и проверить, соответствует ли каждая строка заданной строке, но я не смог этого сделать. Заранее спасибо за помощь. Мой код выглядит следующим образом:

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 ответ

Решение

Используйте.equals для сравнения строк. вы должны заменить temp == "Harry" ... на temp.equals()

Другие вопросы по тегам