Java

Moderators: zibadian
Number of threads: 7836
Number of posts: 18235

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
open directory and read all files Posted by doha786 on 31 Mar 2009 at 8:34 AM
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
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<String> names = new ArrayList<String>();
names.add(word);
for (int i=0; i< names.size() ; i++) {
System.out.println(names.get(i));}



2nd code where i m trying for many files, it has no errors but no output.
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()); 
}


Report
Re: open directory and read all files Posted by KeyCode on 1 Apr 2009 at 5:45 AM
Comparing your code snippets maybe you need to use br instead reader in:
Scanner scan = new Scanner(reader);



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.