Search code examples
javacharacter-encodingdatainputstreamioutils

input string from a file and compare the input string


I want to input strings from a file and check whether each of the string match a given string, but I couldn't make it. Thanks in advance for helping. My code is as following:

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]);
        }
    }

This is my save() function to save strings to a file:

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){}      

}

This is my load() function which returns a string:

    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;
    }

And lastly, my main() function:

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

}

}

Output:

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

Solution

  • Use .equals for string comparison. you should replace temp == "Harry" ... with temp.equals()