open directory and read all files - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

open directory and read all files

doha786doha786 Posts: 1Member
hi,
i m very new in java. right now i m facing one problem to read many files from one folder. suppose i have few txt files in one folder and every txt files contain some my friends name.

my program should open that folder and read all files one by one to find all friends name.

so far i have done it from one particular txt file but i cant make it from many files within a folder.

can anybody pls help me.....
1st code that i used to find from one particular file
[code]
FileReader fr; BufferedReader br;
String result="";
String word= new String();
String target = "friend";


try{ //read one text file
fr = new FileReader ("C:/Users/user/test/new1.txt");
br = new BufferedReader(fr);
Scanner scan = new Scanner(br);

while(scan.hasNext()){ scan.next();
result = scan.findWithinHorizon(target,0);

if(result!=null) {
word = (scan.next() + scan.findWithinHorizon("", 0));

ArrayList names = new ArrayList();
names.add(word);
for (int i=0; i< names.size() ; i++) {
System.out.println(names.get(i));}

[/code]

2nd code where i m trying for many files, it has no errors but no output.
[code]
try{ //read files from folder
File directory = new File("C:/Users/user/test");
String filename[] = directory.list();

for (int i = 0; i < filename.length; i++) {

reader = new FileReader (filename[i]) ;
br = new BufferedReader(reader);
Scanner scan = new Scanner(reader);

while(scan.hasNext()){ scan.next();
result = scan.findWithinHorizon(target,0);

if(result!=null) {
word = (scan.next() + scan.findWithinHorizon("", 0));
System.out.println(word);
}

}
scan.close();
}
}
catch(Exception e){ System.err.println(e.getMessage());
}
[/code]

Comments

  • KeyCodeKeyCode Posts: 43Member
    Comparing your code snippets maybe you need to use br instead reader in:
    Scanner scan = new Scanner(reader);
Sign In or Register to comment.