Java comparing lines in file with String - java

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

Related

algorithm arraylist remove String duplicates and save to new text file

I am currently writing an algorithm that creates an ArrayList from a .txt file, checks it with a loop for duplicates (where the loop should look like this:
Line one is written to new .txt & boolean found is set to true because the string was already found.
Line 2 is written to new .txt etc.
But if two strings are identical, the duplicate, i.e. the second string should just be ignored and continue with the next one).
public class test {
public static void main(String[] args) throws IOException {
String suche = "88 BETRAG-MINUS VALUE 'M'.";
String suche2 = "88 BETRAG-PLUS VALUE 'P'";
boolean gefunden = false;
File neueDatei = new File("C:\\Dev\\xx.txt");
if (neueDatei.createNewFile()) {
System.out.println("Datei wurde erstellt");
}
if (gefunden == false) {
dateiEinlesen(null, gefunden);
ArrayList<String> arr = null;
inNeueDateischreiben(neueDatei, gefunden, arr, suche, suche2);
}
}
public static void dateiEinlesen(File neueDatei, boolean gefunden) {
BufferedReader reader;
String zeile = null;
try {
reader = new BufferedReader(new FileReader("C:\\Dev\\Test.txt"));
zeile = reader.readLine();
ArrayList<String[]> arr = new ArrayList<String[]>();
while (zeile != null) {
arr.add(zeile.split(" "));
zeile = reader.readLine();
}
System.out.println(arr);
} catch (IOException e) {
System.err.println("Error2 :" + e);
}
}
public static void inNeueDateischreiben(File neueDatei, boolean gefunden, ArrayList<String> arr, String suche2,
String suche22) throws IOException {
FileWriter writer = new FileWriter(suche22);
String lastValue = null;
for (Iterator<String> i = arr.iterator(); i.hasNext();) {
String currentValue = i.next();
if (lastValue != null && currentValue.equals(lastValue)) {
i.remove();
{
writer.write(suche2.toString());
gefunden = true;
}
}
writer.close();
}
}
}
Your variable namings (suche2, suche22) makes reading the code difficult.
Other than that, your writing algorithm looks funny. You only compare adjacent lines while duplicate lines could be anywhere. In addition, writer.write only hits when you find a duplicate. Also how you call it and other things don't look right.
Here are some general steps to write this correctly:
Open the file so you can read it line by line.
Create a file writer
Create a set or dictionary like data structure that enables you to look up items in constant time.
For each line that you read do the following:
Look if the line exists in the dictionary.
If not, write it to the new file
If it already exists in the dictionary, skip to step 4.
Add that line to the dictionary for later comparisons and go to step 4.
When the lines are exhausted close both files.
I suggest, you rewrite your code completely as the current version is very difficult to amend.

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.

How to detect new line(or empty line) in a file?

I'm trying to write a program, which reads text from a file that is specified by the user. Now, this program should detect an empty line.
This is what I have unsuccessfully tried:
public static void editFile(String filePath) throws FileNotFoundException, IOException {
file = new File(filePath);
if(file.exists()) {
fileRead = new FileReader(file);
bufferedReader = new BufferedReader(fileRead);
String line = bufferedReader.readLine();
System.out.println(line);
while(line != null) {
line = bufferedReader.readLine();
if(line == "") {
//line = null;
System.out.println("a");
}
System.out.println(line);
}
}
}
To be more clear:
If I'm passing in a text file with for example this text:
test1
test2
test3
test4
it should print 2 a's in the console because of the empty spaces, but it doesn't.
Thank you for your time, I am glad for any suggestion you may have.
This is because the comparison is wrong. You can't use == to compare two strings, you need to use the equals method:
if(line.equals(""))
Since you are checking for empty string, you can also write
if(line.isEmpty())
How do I compare strings in java?
BackSlash is entirely correct, and has answered your question. I'd like to add that your code has some errors:
You're not closing the Reader
You're not testing the first line for blank
You're processing the null value when reaching EOF
The following corrects these errors.
public static void editFile(String filePath) throws IOException
{
File file = new File(filePath);
if (file.exists())
{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try
{
String line;
while ((line = bufferedReader.readLine()) != null)
{
if (line.isEmpty())
{
//line = null;
System.out.println("a");
}
System.out.println(line);
}
} finally {
bufferedReader.close();
}
}
}
Output is:
test1
test2
a
test3
a
test4
Note: You're still printing the blank line in addition to the "a".
What you're doing wrong is that you're comparing the variable itself, not its value with a null string.
Generally there are built-in functions in the string class that return true & false for checking if it's == with something.
if(line.equals("")) { ... }
Or you can just use any alternative way.

Java Buffered Reader, reading line by line

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;

Finding line number of a word in a text file using java

I require searching a word in a text file and display the line number using java. If it appears more than once I need to show all the line numbers in the output. Can anyone help me please?
Read the text file using Java class LineNumberReader and call method getLineNumber to find the current line number.
http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
Something like this might work:
public ArrayList<Integer> find(String word, File text) throws IOException {
LineNumberReader rdr = new LineNumberReader(new FileReader(text));
ArrayList<Integer> results = new ArrayList<Integer>();
try {
String line = rdr.readLine();
if (line.indexOf(word) >= 0) {
results.add(rdr.getLineNumber());
}
} finally {
rdr.close();
}
return results;
}
You can store this information manually. Whenever you are invoking readline() of your BufferedReader, if you're using such, you can also increment a counter by one. E.g.,
public int grepLineNumber(String file, String word) throws Exception {
BufferedReader buf = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file))));
String line;
int lineNumber = 0;
while ((line = buf.readLine()) != null) {
lineNumber++;
if (word.equals(line)) {
return lineNumber;
}
}
return -1;
}

Categories

Resources