Amazon Interview Question
Software Engineer / Developersgrep -l keyword *
OR
ls * | grep -l keyword
I don't have unix prompt but one of those should word, * will search recursively on sub directories
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class fileOperation {
public static void main(String[] args) throws IOException {
String loc = "temp";
File dir = new File(loc);
listRecursive(dir);
}
private static void listRecursive(File dir) throws IOException {
File[] listFiles = dir.listFiles();
if(listFiles != null){
for(int i=0;i<listFiles.length;i++){
if(listFiles[i].isDirectory()){
listRecursive(listFiles[i]);
}else{
//System.out.println(listFiles[i]);
checkPhoneNumber(listFiles[i]);
}
}
}
}
private static void checkPhoneNumber(File file) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ( (line = br.readLine()) != null)
{
// Print phone number to screen
try{
long num = Long.parseLong(line);
System.out.println(file.getAbsolutePath());
System.out.println(num);
}catch (NumberFormatException ne){
//System.out.println("NE");
}
//System.out.println (line);
}
br.close();
}
}
<pre lang="" line="1" title="CodeMonkey71065" class="run-this">/* The class name doesn't have to be Main, as long as the class is not public. */
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String s;
while (!(s=r.readLine()).startsWith("42")) System.out.println(s);
}
}
</pre><pre title="CodeMonkey71065" input="yes">
23</pre>
Make depth-first search using stack for example.
- m@}{ April 20, 2011