i m very new in java. now facing prob to get char/string after a particular string from txt file. suppose i have few text files in one folder and every txt files contain some line like my first friend jocky, second friend vicky and so on.....:$

my program should open that folder and read all files to find what is the next character of string 'friend'. :'(

is it possilbe ?:icon_question: ? pls help me...............:X

Recommended Answers

All 4 Replies

Simple program to read ONE file:

BufferedReader reader = new BufferedReader(new FileReader("filename.txt"));

String line = reader.readLine();
while (line!=null) {
  // line read is not null
// do things with the line
...
..
.


// read the next line and go to the beginning of the while. If it is null
// you exit the while because the file is over

line = reader.readLine();
}

reader.close();

API for File: http://java.sun.com/javase/6/docs/api/java/io/File.html
You will find a method that returns all the contents of a folder. check which of these are files and read them.

thank u so much for ur kind help.... i almost done my job but right now its showing full line after my target string 'friend'.
i want only one char/string after my particular string. the code is :

import java.io.*;
import java.util.*;
import java.lang.*;

class subString2 {

public static void main(String[] args){

FileReader fr;
BufferedReader br;
String append="";
String word= new String();
int x;
String target = "friend";
String space = new String(" ");

try {
fr = new FileReader ("C:/Users/user/Desktop/java/test.txt");
br = new BufferedReader(fr);


while ((append = br.readLine()) != null) {
x = append.toLowerCase().indexOf(target);
if (x>=0) {
 word=append.substring(append.indexOf(target)+6);
 
 System.out.println (word);
 
}
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}

output :
jocky
vicky sdkafjlkasdjflksadjflkasd
rocky dfjksd, lksdjf

You'll need add some code to separate that piece then. You could do that with:
a) regular expressions, which I posted a link about above
b) String.split() on spaces and step through the resulting array to identify the parts that you want to keep
c) step through the line of text with more calls to indexOf() to find the substring of interest

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.