Reputation: 33
I tried this:
public static void ReadRecord()
{
String line = null;
try
{
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
line = br.readLine();
while(line != null)
{
System.out.println(line);
}
br.close();
fr.close();
}
catch (Exception e)
{
}
}
}
It non stop and repeatedly reads only one record that i had inputtd and wrote into the file earlier...How do i read records and use tokenization in reading records?
Upvotes: 0
Views: 4133
Reputation: 671
For a text file called access.txt locate for example on your X drive, this should work.
public static void readRecordFromTextFile throws FileNotFoundException
{
try {
File file = new File("X:\\access.txt");
Scanner sc = new Scanner(file);
sc.useDelimiter(",|\r\n");
System.out.println(sc.next());
while (sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();// closing the scanner stream
} catch (FileNotFoundException e) {
System.out.println("Enter existing file name");
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 2188
You have to read the lines in the file repeatedly in the loop using br.readLine()
. br.readLine()
reads only one line at time.
do something like this:
while((line = br.readLine()) != null) {
System.out.println(line);
}
Check this link also if you have some problems. http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
If you want to split your string into tokens you can use the StringTokenizer
class or can use the String.split()
method.
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
st.hasMoreTokens()
- will check whether any more tokens are present.
st.nextToken()
- will get the next token
String[] result = line.split("\\s"); // split line into tokens
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
line.split("\\s")
- will split line
with space
as the delimiter. It returns a String array.
Upvotes: 3
Reputation: 2286
Try This :
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
while((line=br.readline())!=null)
System.out.println(line);
Upvotes: 0
Reputation: 5327
try this
while((line = br.readLine()) != null)
{
System.out.println(line);
}
Upvotes: 1