slidepuppy1
slidepuppy1

Reputation: 1

how do you search for something in an array in java

I wan to create a public, non-static method that does this:

getContent : This method should take as input a String filename and return a String. The method should search for a file with name filename in the array drive and return the data that is stored in that TxtFile. If no such file exists in the array drive, the method should return null.

I don't know how to search for something in an array. can someone show me how to do this?

Upvotes: 0

Views: 1654

Answers (3)

Aman
Aman

Reputation: 548

this should be of help: File search

A definitive source for information.

EDIT: thought of something really simple:

String[] drives = new String[]{"C:\\", "D:\\"};
File file;

for(String drive : drives)
{
    file = new File(drive + "abc.txt");
    JOptionPane.showMessageDialog(null, file.exists());
}

you can replace the showMessageDialogBox with whatever you want to do if the file exists.

Upvotes: 0

ManuPK
ManuPK

Reputation: 11829

Come on, try it your self:

Step1: Read all the file Names from a directory.

Step2: Store the list of Files to a List.

Step3: Iterate the list, Write a conditions with a use the File.getName() method to compare and the name and your input.

if(file.getName().equals(inputFileName)){
   return "boooo! I have found You!"  
}

Upvotes: 3

Jens Schauder
Jens Schauder

Reputation: 81862

You search in an array by iterating of it. Something like this (if you are inside a method):

for(String x : someStringArray){
    if (somecondition(x))  return x;
}

Upvotes: 1

Related Questions