Java Buffered Reader, reading line by line - java

Hey I have the following method that checks if a word is a legitimate word by looking through a large .txt file and checking if the word is there. Right now the method only works properly if the words in the .txt file are on the same line with only one space between one another. Is there any way I can make it so it reads through the list of words line by line; if there is one word per line. For example if the .txt file is oriented like this:
word1
word2
Here is my method:
private boolean isWord(String word){
try{
//search .txt file of valid words. !!Will only read properly if there is a single space between each word.
BufferedReader in = new BufferedReader(new FileReader("/Users/user/Documents/workspace/AnagramAlgorithm/src/words.txt"));
String str;
while ((str = in.readLine()) != null){
if (str.indexOf(word) > -1){
return true;
}
else{
return false;
}
}
in.close();
}
catch (IOException e){
}
return false;
}

In your code if the first line does not contain the word you immediately return false. Change it to only return false when you went through the complete file:
while ((str = in.readLine()) != null){
if (str.equals(word)){
return true;
}
}
return false;

Related

Delete multiple lines from text file

I am trying to create a method to delete some of the text from my txt file. I started by checking if a string that I have exist in the file:
public boolean ifConfigurationExists(String pathofFile, String configurationString)
{
Scanner scanner=new Scanner(pathofFile);
List<String> list=new ArrayList<>();
while(scanner.hasNextLine())
{
list.add(scanner.nextLine());
}
if(list.contains(configurationString))
{
return true;
}
else
{
return false;
}
}
Since the string I want to delete contains multiple lines (String configurationString = "This\nis a\n multiple lines\n string";) I started by creating a new array of strings and splitting the string into array members.
public boolean deleteCurrentConfiguration(String pathofFile, String configurationString)
{
String textStr[] = configurationString.split("\\r\\n|\\n|\\r");
File inputFile = new File(pathofFile);
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(textStr[0])) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
return true;
}
Can someone please help on how to delete the string from the txt file and also the line before and after the string?
There are many different ways to do this, though one way I do it is to firstly read the files content into an array of Strings by line (looks like you already did this), then to remove the data you don't want, and write to the file line-by-line the new information you do want.
To remove lines before the line you don't want, the line you don't want, and the line after you don't want, you could something like this:
List<String> newLines=new ArrayList<>();
boolean lineRemoved = false;
for (int i=0, i < lines.length; i++) {
if (i < lines.length-1 && lines.get(i+1).equals(lineToRemove)) {
// this is the line before it
} else if (lines.get(i).equals(lineToRemove)) {
// this is the line itself
lineRemoved = true;
} else if (lineRemoved == true) {
// this is the line after the line you want to remove
lineRemoved = false; // set back to false so you don't remove every line after the one you want
} else
newLines.add(lines.get(i));
}
// now write newLines to file
Note that this code is rough and untested, but should get you where you need to be.

Scanner only searching first line of .txt file

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
}
}

How to clear BufferedReader if it isn't empty [Java/Android]

I don't understand how to clear a BufferedReader. When I push button in Activity, the variable is set to 1 or 2. Depend on number change file in BufferedReader. When I push second time in buffer will be two files. How to tell BR to clear buffer before second will be upload. And vice versa, of course.
public List<String> getQuestionLinesList() {
String line;
List<String> lines = new ArrayList<String>();
Log.d(TAG, " Trying to get resourses");
Resources res = context.getResources();
try {
if (selectedBox == 1) {
bufferedQuestions = new BufferedReader(new InputStreamReader(res.openRawResource(R.raw.questions_list)));
} else if (selectedBox == 2) {
bufferedQuestions = new BufferedReader(new InputStreamReader(res.openRawResource(R.raw.questions_list_art)));
}
Log.d(TAG, "number i = " + Integer.toString(selectedBox));
while ((line = bufferedQuestions.readLine()) != null) {
lines.add(line);
Log.d(LINETAG, line);
}
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
Maybe you can try using a local variable in your method for BufferedReader not "bufferedQuestions" that you probably declared like a field in the class where that method : "getQuestionLinesList" belongs.
Add a carriage/ \n at the end of your files, then readLine() should be able to clear your BufferedReader.
JavaDocs for BufferedRead which states
public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Java comparing lines in file with String

I'm experiencing an strange issue with a file in Java...
I want to compare every line of this file with a string (host variable), but (I don't know why), the while loop is always comparing the first line of the file and ignores the second line, the third...
Here's the code:
fr = new FileReader (file);
inf = new BufferedReader(fr);
String l;
while ((l=inf.readLine()) != null) {
if (host.contains(l))
return true;
else
return false;
}
Any help would be appreciated...
Two problems:
You are finding the line in the host name - that's like finding a haystack in a needle - reverse the test
No matter the result of the condition, you return after testing it just once, so only the first line is tested
Instead, try this:
String l;
while ((l=inf.readLine()) != null)
if (l.contains(host))
return true;
return false;
It should be host.equals(l), or possibly l.contains(host). It depends what you want to do.
It's only testing the first line in your file because of the if/else statement in the loop. Either branch results in a return thus stopping the rest of the file's contents from being processed.
Maybe you should return false only after you've reached the end of your file?
fr = new FileReader (file);
inf = new BufferedReader(fr);
String l;
while((l=inf.readLine())!=null){
if (host.contains(l))
return true;
}
return false;
Suppose you are looking for the host string in the file. You could possible do it like this.
public boolean contains(Reader in, String word) throws IOException {
BufferedReader inf = new BufferedReader(in);
String l;
boolean found = false;
while((l=inf.readLine())!=null){
if (l.contains(word)) {
found = true;
break;
}
}
return found;
}

Find a string (or a line) in a txt File Java

let's say I have a txt file containing:
john
dani
zack
the user will input a string, for example "omar"
I want the program to search that txt file for the String "omar", if it doesn't exist, simply display "doesn't exist".
I tried the function String.endsWith() or String.startsWith(), but that of course displays "doesn't exist" 3 times.
I started java only 3 weeks ago, so I am a total newbie...please bear with me.
thank you.
Just read this text file and put each word in to a List and you can check whether that List contains your word.
You can use Scanner scanner=new Scanner("FileNameWithPath"); to read file and you can try following to add words to List.
List<String> list=new ArrayList<>();
while(scanner.hasNextLine()){
list.add(scanner.nextLine());
}
Then check your word is there or not
if(list.contains("yourWord")){
// found.
}else{
// not found
}
BTW you can search directly in file too.
while(scanner.hasNextLine()){
if("yourWord".equals(scanner.nextLine().trim())){
// found
break;
}else{
// not found
}
}
use String.contains(your search String) instead of String.endsWith() or String.startsWith()
eg
str.contains("omar");
You can go other way around. Instead of printing 'does not exist', print 'exists' if match is found while traversing the file and break; If entire file is traversed and no match was found, only then go ahead and display 'does not exist'.
Also, use String.contains() in place of str.startsWith() or str.endsWith(). Contains check will search for a match in the entire string and not just at the start or end.
Hope it makes sense.
Read the content of the text file: http://www.javapractices.com/topic/TopicAction.do?Id=42
And after that just use the textData.contains(user_input); method, where textData is the data read from the file, and the user_input is the string that is searched by the user
UPDATE
public static StringBuilder readFile(String path)
{
// Assumes that a file article.rss is available on the SD card
File file = new File(path);
StringBuilder builder = new StringBuilder();
if (!file.exists()) {
throw new RuntimeException("File not found");
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder;
}
This method returns the StringBuilder created from the data you have read from the text file given as parameter.
You can see if the user input string is in the file like this:
int index = readFile(filePath).indexOf(user_input);
if ( index > -1 )
System.out.println("exists");
You can do this with Files.lines:
try(Stream<String> lines = Files.lines(Paths.get("...")) ) {
if(lines.anyMatch("omar"::equals)) {
//or lines.anyMatch(l -> l.contains("omar"))
System.out.println("found");
} else {
System.out.println("not found");
}
}
Note that it uses the UTF-8 charset to read the file, if that's not what you want you can pass your charset as the second argument to Files.lines.

Categories

Resources