Migrators said:
Respected sir,
I am having a text File and I have to read that file string by string
and I have to store these strings I an array of String. How can I
acheive this.
Kindly help us.
Sir, your grammar suggests you are not a native English speaker. So
I am guessing that by "string" you mean sentence, and that your text
files may not be in English.
In that case, no one has yet given you a useful answer. Following is my
solution of the general case where you want to get all *sentences* from
a file, whatever the language/locale. The java.text.BreakIterator class
"should" deal with this problem; however, it is designed to parse String
objects, not file streams. Hence the following kind of code is needed:
--------------------------------------------------------------------
import java.io.*;
import java.text.*;
import java.util.*;
/**
* Utilities for searching through files.
* Creation date: (12/22/2003 9:13:07 AM)
* @author: <A href=mailto:
[email protected]>Tony Dahlman</A>
*/
public class FileSentenceReader {
/**
* Reads through a text file, parsing it into sentences
* in sound i18n fashion. Returns an ArrayList of the
* sentences.
*/
public static ArrayList getAllSentences( File f ) {
BreakIterator sIter = BreakIterator.getSentenceInstance();
ArrayList aL = new ArrayList();
char[] text = new char[1024];
try{
BufferedReader ins = new BufferedReader(
new FileReader( f ) );
String stub = new String("");
int chCount = 1024;
while( chCount > 0 ) {
chCount = ins.read( text, 0, 1024 - stub.length() );
// build a string for the iterator from the stream
StringBuffer sbuf = new StringBuffer( 1024 );
// reinsert leftover chars from prev loop
sbuf.append( stub );
sbuf.append( text );
String str = sbuf.toString();
sIter.setText( str );
int start = sIter.first();
for( int end = sIter.next();
end != BreakIterator.DONE;
start = end, end = sIter.next() ) {
aL.add( str.substring( start, end ) );
}
// remaining chars at end of read buffer
stub = (String)aL.remove( aL.size() - 1);
text = new char[1024];
}
ins.close();
} catch( IOException ioe ) {
ioe.printStackTrace();
}
return aL;
}
// test code
public static void main(String[] args) {
if( args.length != 1 )
return;
File f = new File( args[0] );
if( !f.exists() )
return;
if( f.isDirectory() || ! f.canRead() )
return;
ArrayList aL = FileSentenceReader.getAllSentences( f );
System.out.println("Found " + aL.size() + " sentences in file "
+ f );
Iterator i = aL.iterator();
while( i.hasNext() )
System.out.println( (String)i.next() );
}
}