Search code examples
javafile-ioarraylistnio

Search text From Arraylist


Source Code GitHub i'm Working File Handing Library Project.Books Data Save in a File Name NameList.txt

Ready whole File and save into ArrayList then try to search a Book Name "Head First jQuery" But can find. please help how can i find Desire Text From Arraylist for Text file .

Note When i move text for txt file to arraylist a whole line copy where BookID ,Name & publish name there , but want search only Book name

public static void main(String[] args) throws IOException {

    Path Source=Paths.get("NameList.txt");
    Charset charset=Charset.forName("US-ASCII");
    ArrayList<String> lines=new ArrayList<String>();
    try (BufferedReader reader=Files.newBufferedReader(Source,charset))
    {
        String str=null;
        while((str=reader.readLine())!=null){
            System.out.println(str);
            lines.add(str);

        }

    } catch (Exception e) {
        e.getMessage();
    }
    Iterator<String> iterator =lines.iterator();

    for(int i=0;i<lines.size();i++){
        if(lines.get(i)=="Head First jQuery"){
            System.out.println("find");
            break;
        }

    }

Solution

  • Your code

    if(lines.get(i)=="Head First jQuery")
    

    will always evaluate to false as both references compared point to two different String instances. You should compare Strings using equals() or equalsIgnoreCase() methods.

    I would suggest leave the comparison to ArraysList's contains() method instead of you doing it.

                if(lines.contains("Head First jQuery")) {
                    System.out.println("find");
                }