Basically, i need to check for a word's occurances within multiple files.
Also, a word might exist in a single text file multiple times.
I want to save positions of a word for each file; so i wrote the code below:
public static void findWord(String word, File file){
try{
BufferedReader input = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
ArrayList<Integer> list=new ArrayList<Integer>();
while((line=input.readLine())!=null){
if(line.indexOf(word)>-1){
list.add(line.indexOf(word));
}
}
System.out.println(file +": "+ list);
input.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
My code fails to add to list after first successful occurance. So I have only one element within every array.
How do i fix it?
P.S My text files consists of one line
Here goes the fix (replace your while loop with this):
while ((line = input.readLine ()) != null)
{
int index = -1;
while ((index = line.indexOf (word, index + 1) > -1)
{
list.add (index);
}
}
Related
I read about someone having troubles with BufferedReader: the reader simply do not read the first lines. I have instead the opposite problem. For example, in a text file with 300 lines, it arrives at 200, read it half of it and then the following string is given null, so it stops.
private void readerMethod(File fileList) throws IOException {
BigInteger steps = BigInteger.ZERO;
BufferedReader br = new BufferedReader(new FileReader(fileList));
String st;
//reading file line by line
try{
while (true){
st = br.readLine();
if(st == null){
System.out.println("Null string at line " + steps);
break;
}
System.out.println(steps + " - " + st);
steps = steps.add(BigInteger.ONE);
}
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
br.close();
}catch(Exception e){}
}
}
The output of the previous slice of code is as expected until it reaches line 199 (starting from 0). Consider a file with 300 lines.
...
198 - 3B02D5D572B66A82F9D21EE809320DB3E250C6C9
199 - 6E2C69795CB712C27C4097119CE2C5765
Null string at line 200
Notice that, all lines have the same length, so in this output line 199 is not even complete. I checked the file text, and it's correct: it contains all 300 lines and they are all of the same length. Also, in the text there are only capitals letters and numbers, as you can see.
My question is: how can i fix this? I need that the BufferedReader read all the text, not just a part of it.
As someone asked i add here the remaining part of the code. Please notice that all capital names are constant of various type (int, string etc).
This is the method that is called by the main thread:
public void init(){
BufferedWriter bw = null;
List<String> allLines = createRandomStringLines(LINES);
try{
String fileName = "SHA1_encode_text.txt";
File logFile = new File(fileName);
System.out.println(logFile.getCanonicalPath());
bw = new BufferedWriter(new FileWriter(logFile));
for(int i = 0; i < allLines.size(); i++){
//write file
String o = sha1FromString(allLines.get(i));
//sha1FromString is a method that change the aspect of the string,
//replacing char by char. Is not important at the moment.
bw.write(o + "\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
bw.close();
}catch(Exception e){}
}
}
The method that create the list of random string is the following. "SYMBOLS" is just a String contains all avaiable chars.
private List<String> createRandomStringLines(int i) {
List<String> list = new ArrayList<String>();
while(i!=0){
StringBuilder builder = new StringBuilder();
int count = 64;
while (count-- != 0) {
int character = (int)(Math.random()*SYMBOLS.length());
builder.append(SYMBOLS.charAt(character));
}
String generatedString = builder.toString();
list.add(generatedString);
i--;
}
return list;
}
Note that, the file written is totally correct.
Okay, thanks to the user ygor, i manage to resolve it. The problem was that the BufferReader stars his job when the BufferWriter isn't closed yet. It was sufficient to move the command line that require the reader to work, after the bufferWriter.close() command.
I am new in java. I just wants to read each string in java and print it on console.
Code:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = new String();
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
System.out.println(""+data);
}
} catch (IOException e) {
// Error
}
}
If file contains:
Add label abc to xyz
Add instance cdd to pqr
I want to read each word from file and print it to a new line, e.g.
Add
label
abc
...
And afterwards, I want to extract the index of a specific string, for instance get the index of abc.
Can anyone please help me?
It sounds like you want to be able to do two things:
Print all words inside the file
Search the index of a specific word
In that case, I would suggest scanning all lines, splitting by any whitespace character (space, tab, etc.) and storing in a collection so you can later on search for it. Not the question is - can you have repeats and in that case which index would you like to print? The first? The last? All of them?
Assuming words are unique, you can simply do:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
ArrayList<String> words = new ArrayList<String>();
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = null;
while ((data = infile.readLine()) != null) {
for (String word : data.split("\\s+") {
words.add(word);
System.out.println(word);
}
}
} catch (IOException e) {
// Error
}
// search for the index of abc:
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals("abc")) {
System.out.println("abc index is " + i);
break;
}
}
}
If you don't break, it'll print every index of abc (if words are not unique). You could of course optimize it more if the set of words is very large, but for a small amount of data, this should suffice.
Of course, if you know in advance which words' indices you'd like to print, you could forego the extra data structure (the ArrayList) and simply print that as you scan the file, unless you want the printings (of words and specific indices) to be separate in output.
Split the String received for any whitespace with the regex \\s+ and print out the resultant data with a for loop.
public static void main(String[] args) { // Don't make main throw an exception
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(fstream));
String data;
while ((data = infile.readLine()) != null) {
String[] words = data.split("\\s+"); // Split on whitespace
for (String word : words) { // Iterate through info
System.out.println(word); // Print it
}
}
} catch (IOException e) {
// Probably best to actually have this on there
System.err.println("Error found.");
e.printStackTrace();
}
}
Just add a for-each loop before printing the output :-
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
for(String temp : data.split(" "))
System.out.println(temp); // no need to concatenate the empty string.
}
This will automatically print the individual strings, obtained from each String line read from the file, in a new line.
And afterwards, I want to extract the index of a specific string, for
instance get the index of abc.
I don't know what index are you actually talking about. But, if you want to take the index from the individual lines being read, then add a temporary variable with count initialised to 0.
Increment it till d equals abc here. Like,
int count = 0;
for(String temp : data.split(" ")){
count++;
if("abc".equals(temp))
System.out.println("Index of abc is : "+count);
System.out.println(temp);
}
Use Split() Function available in Class String.. You may manipulate according to your need.
or
use length keyword to iterate throughout the complete line
and if any non- alphabet character get the substring()and write it to the new line.
List<String> words = new ArrayList<String>();
while ((data = infile.readLine()) != null) {
for(String d : data.split(" ")) {
System.out.println(""+d);
}
words.addAll(Arrays.asList(data));
}
//words List will hold all the words. Do words.indexOf("abc") to get index
if(words.indexOf("abc") < 0) {
System.out.println("word not present");
} else {
System.out.println("word present at index " + words.indexOf("abc"))
}
I'm in a beginning programming class, and seem to be having a major issue with searching a text file. What my code should do, based on the assignment:
Accept input, in this case a name and place that input into a .txt file
Allow the user to search for a name, or part of a name, and return all lines with matching text.
I have the input portion of the assignment complete, and am on the verge on completing the retrieval portion, but my code only searches the first line of the .txt file. I am able to print out all lines of the .txt file, and if I search for the name in Line 1 of the .txt file, it will print the line correctly. My issue comes when I am searching for a name that is not on Line 1. Below is my code:
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
if (choice == 2 && retrieve.equalsIgnoreCase("YES") || retrieve.equalsIgnoreCase("Y"))
{
while (retrieve2.equalsIgnoreCase("YES") || retrieve2.equalsIgnoreCase("Y"))
{
FileReader reader = new FileReader("Name_Index.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
System.out.println ("Enter a string of characters in which to search by or enter \"all names\" f$
search_term = gatherInput();
System.out.println("Search results include: ");
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = new Scanner (new File("Name_Index.txt"));
inFile.useDelimiter(",");
while (inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
Collections.sort(list);
if (search_term.equalsIgnoreCase("all names"))
{
for (String temp : list)
{
System.out.println(temp);
}
}
else if (line.toLowerCase().contains(search_term.toLowerCase()))
{
System.out.println(line);
bufferedReader.close();
}
System.out.println("End!");
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve2=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
System.out.println("Thank you, come again!");
}
}
public static String gatherInput()
{
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
return user_input;
}
}
I have tried expanding the while (inFile.hasNextLine()) loop to include the second "if" statement, however that creates an issue for the "all names" search - it returns the entire list multiple times (however many lines are in the file). I have even tried creating another while (inFile.hasNextLine()) loop within the second "if" statement, and there is no difference in outcome.
I'm so frustrated at this point, because I've been working on this code for over a week, and have reviewed all of my notes and lecture recordings for this assignment with no help. Any insight would be much appreciated.
You are reading only 1 line of the file
String line = bufferedReader.readLine();
Why don't you read all lines and store them in a List;
List<String> lines = new ArrayList<>();
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
Then to print all lines containing a substring ignorecase:
lines.stream().filter(l -> l.toLowerCase().contains(search_term.toLowerCase))
.forEach(s -> System.out.println(s));
You need to loop the readLine()
For example:
File f = new File(ruta);
if(!f.exists()) //Error
else {
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
//line = the next line
}
}
we are supposed to create a program that reads a word from a JTextField and compare it to a list, then we have to count how many lines to the word if it exist and display the same line from another text file in the same program into another JTextField (it's supposed to be a Dictionary of some sort) here is what i have:
boton1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String palabra=tx1.getText();
boton3.setEnabled(true);
try{
// here is where i open my file
FileInputStream fstream = new FileInputStream("src/archivos/translator.txt");
DataInputStream entrada = new DataInputStream(fstream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
String strLinea;
while ((strLinea = buffer.readLine()) != null) {
System.out.println (strLinea);
int i=0;
while (!(strLinea.equals(palabra))){
i++;
}
tx2.setText(String.valueOf(i));
}
entrada.close();
}catch (IOException x){
System.err.println("Oh no, ocurriĆ³ un error: " + x.getMessage());
}
}} );
Based on my understanding of what you said, first, you should change:
while (!(strLinea.equals(palabra))){
to
while (!(strLinea.contains(palabra))){
You want to see if the line contains that word, not that the line is the same as the contents of the TextArea. Also, you'll want to add another statement to the contents of that while loop. Currently it'll just increment "i" forever if the word doesn't come up in the document. You want it to move strLinea to the next line if the current one doesn't have it, and if it does, you'll then want to terminate the loop.
I think your problem is
while ((strLinea = buffer.readLine()) != null) {
System.out.println (strLinea);
int i=0;
while (!(strLinea.equals(palabra))){
i++;
}
tx2.setText(String.valueOf(i));
}
In inner while loop, you are iterating forever. If you want to compare each word in the file to the JTextField value, you should write
int i = 0;
while ((strLinea = buffer.readLine()) != null) {
i++;
System.out.println (i + " " + strLinea);
if (strLinea.equals(palabra)){
tx2.setText(String.valueOf(i));
break;
}
}
My app needs to read from several files in the assets folder. But my file has delimiters $$$ and ||. The structure of the file is like this.
Construction$$$
All the work involved in assembling resources and
putting together the materials required to form a new or changed
facility.||
Construction Contractor$$$
A corporation or individual
who has entered into a contract with the organization to perform
construction work.||
The sentences ending with $$$ are to be stored in seperate array list and the sentences ending with || are to be stored on seperate array list.
How can i do this? Any sample or example code will be appreciated. Note that these files are very long.
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("c.txt"))); //throwing a FileNotFoundException?
String word;
while((word=br.readLine()) != null)
A_Words_array.add(word); //break txt file into different words, add to wordList
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try {
br.close(); //stop reading
}
catch(IOException ex) {
ex.printStackTrace();
}
}
String[]words = new String[A_Words_array.size()];
A_Words_array.toArray(words); //make array of wordList
for(int i=0;i<words.length; i++)
Log.i("Read this: ", words[i]);
Above is the code i found now how to split my sentences based upon ending delimiters?
Asuming that each sentence is in one line and they finish either with $$$ or ||, you can store the lines in different arrays depending on its endings:
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
String line;
while (line = br.readLine()) != null) {
if (line.endsWith("$$$")) {
list1.add(line);
} else {
list2.add(line);
}
}
String[] dollarlines = list1.toArray(new String[list1.size()]);
String[] verticalLines = list2.toArray(new String[list2.size()]);