Find a string (or a line) in a txt File Java - 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.

Related

split method to output values under each other when reading from a file

My code works fine however it prints the values side by side instead of under each other line by line. Like this:
iatadult,DDD,
iatfirst,AAA,BBB,CCC
I have done a diligent search on stackoverflow and none of my solution's seem to work. I know that I have to make the change while the looping is going on. However none of the examples I have seen have worked. Any further understanding or techniques to achieve my goal would be helpful. Whatever I am missing is probably very small. Please help.
String folderPath1 = "C:\\PayrollSync\\client\\client_orginal.txt";
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
if(line.contains("fooa")||line.contains("foob")){
fileContents.add(line);
}
//---------------------------------------
}
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents);
Add a Line Feed before you add to fileContents.
fileContents.add(line+"\n");
By printing the list directly as you are doing you are invoking the method toString() overridden for the list which prints the contents like this:
obj1.toString(),obj2.toString() .. , objN.toString()
in your case the obj* are of type String and the toString() override for it returns the string itself. That's why you are seeing all the strings separated by comma.
To do something different, i.e: printing each object in a separate line you should implement it yourself, and you can simply append the new line character('\n') after each string.
Possible solution in java 8:
String result = fileContents.stream().collect(Collectors.joining('\n'));
System.out.println(result);
A platform-independent way to add a new line:
fileContents.add(line + System.lineSeparator);
Below is my full answer. Thanks for your help stackoverflow. It took me all day but I have a full solution.
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
String [] names ={"iatdaily","iatrapala","iatfirst","wpolkrate","iatjohnson","iatvaleant"};
if (Stream.of(names).anyMatch(line.trim()::contains)) {
System.out.println(line);
fileContents.add(line + "\n");
}
}
System.out.println("---------------");
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}

How to neglect blank spaces in a string search in html file using java?

I have a html file which I have to search line by line and look for a particular string and then take some actions accordingly.
The problem is that the string is being matched to the entire line of the each line of the html file.
So if there are some spaces before the actual string in a given line, the match turns out to be false, even though it should be positive.
package read_txt;
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.html");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
//String a = "media query";
switch (strLine) {
case "#media query" :
System.out.println("media query found");
System.out.println("html file responsive");
break;
// default :
// System.out.println("html file unresponsive");
//break;
}
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
In my code above, I am searching for a String "media query". Now suppose this is the html file being searched :
The codes works fine for this html file, but now suppose we have this html file :
The string match does not work although a media query string is present, but if I change the matched string to " media query" instead of "media query", it works again.
Any idea how can I ignore the blank spaced occurring before appearance of any text in a line?
In this case, I would think that using "switch" is not the right way to go.
You might use
if (strLine.contains("media query"))
but that will fail if the line has "media query" (two spaces instead of one).
So, you best bet might be to use a regular expression.
You could use endsWith, e.g.
if (strLine.endsWith("media query")) { ...
In cases, where the searched string could be somewhere in the middle of line you could use indexOf, e.g.
if (strLine.indexOf("medial quera") >= 0) { ...

Check if a string/line that is going to write into a text file is already exist in the text file

I am analyzing a web access log and try to find out all the unique object (any file or any path) that were requested only once in the access log. Every time the program write into the text file, the content of the text file looks like this :
/~scottp/publish.html
/~ladd/ostriches.html
/~scottp/publish.html
/~lowey/
/~lowey/kevin.gif
/~friesend/tolkien/rootpage.html
/~scottp/free.html
/~friesend/tolkien/rootpage.html
.
.
.
I want to check if the line which is going to write into the text file is already exist in the text file. In order words, if it's does exist in the text file, then do nothing and skip it and analyze the next line. If not, then write it into the text file.
I tried to use equals or contains but it doesn't seems to be work, here's a little pieces of my code:
// Find Unique Object that were requested only once
if (matcher3.find()) {
if(!requestFileName.equals(bw.equals(requestFileName))) {
bw.write(requestFileName);
bw.newLine();
}
}
What should I do to actually perform a check ?
As #JB Nizet commented you should make use of Set
Set<String> set = new HashSet<String>();
BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/yourFile.txt")));
String line;
while((line = reader.readLine()) != null) {
// duplicate
if(set.contains(line))
continue;
set.add(line);
// do your work here
}
Perhaps something simple like this:
try (BufferedReader br = new BufferedReader(new FileReader(yourFilePath))) {
boolean lineExists = false;
String currentLine;
while ((currentLine = br.readLine()) != null) {
if (currentLine.trim().equalsIgnoreCase(requestFileName.trim())) {
lineExists = true;
break;
}
}
br.close();
if (!lineExists) {
bw.write(requestFileName);
bw.newLine();
}
}
catch (IOException e) {
// Do what you want with Exception...
}

Java extract text from text file from a certain point on the text

I have created a method with BufferedReader that opens a text file created previously by the program and extracts some characters. My problem is that it extracts the whole line and I want to extract only after a specified character, the :.
Here is my try/catch block:
try {
InputStream ips = new FileInputStream("file.txt");
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br1 = new BufferedReader(ipsr);
String ligne;
while((ligne = br1.readLine()) != null) {
if(ligne.startsWith("Identifiant: ")) {
System.out.println(ligne);
id = ligne;
}
if(ligne.startsWith("Pass: ")) {
System.out.println(ligne);
pass = ligne;
}
}
System.out.println(ligne);
System.out.println(id);
System.out.println(pass);
br1.close();
} catch (Exception ex) {
System.err.println("Error. "+ex.getMessage());
}
At the moment, I return to my String id the entire ligne, and same for pass – by the way, all the sysout are tests and are useless there.
If anybody knows how to send to id the line after the :and not the entire line, I probably searched bad, but google wasn't my friend.
Assuming there's only one : symbol in the string you can go with
id = ligne.substring(ligne.lastIndexOf(':') + 1);
Use StringUtils
StringUtils.substringAfter(id ,":"),
Why don't you try to do a split() on ligne?
If you use String[] splittedLigne = ligne.split(":");, you will have the following in splittedLigne:
splittedLigne[0] -> What is before the :
splittedLigne[1] -> What is after the :
This will give you what you need for every line. Also, this will work for you if you have more than one :.

How can I rename a file in Java?

My purpose is to rename one file. What I'm doing is: I'm searching a particular string in a text file. Among So many files and if that particular text is found then I want rename that text file with a given string.
Here is what I have tried:
String opcode="OPCODES"; // String that I want to search.
File file = new File("D:\\CFF1156"); // All files are inside this folder.
System.out.println("The File Name is :"+file.getName());
File[] f = file.listFiles();
System.out.println("The Length of File is :"+f.length);
Boolean flag=false;
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
for(int i=0;i<f.length;i++)
{
try{
reader = new BufferedReader(new FileReader(f[i]));
String text = null;
while ((text = reader.readLine()) != null)
{
if(text.contains(opcode))
{
System.out.println("Found");
System.out.println("The File Containing the Search text is :"+f[i]);
f[i].renameTo(new File("D://CFF1156/changed.txt"));
System.out.println("renamed :"+(f[i].renameTo(new File("D://CFF1156/changed.txt"))));
if(f[i].renameTo(new File("D://CFF1156/changed.txt")))
{
System.out.println("Successfully renamed");
}
else
{
System.out.println("Error");
}
}
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (reader != null)
{
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
The above code is searching the particular file. But I'm not able to rename it.
What would be a working Solution to this problem?
You are renaming with the same name, in a loop. Fix that thing first. Furthermore, take the returned boolean value in a variable by renameTo() method, and use that variable in your if.
I am having a hard time reading the code as given, but there is a renameTo method on File (see this javadoc). Note that it takes a File object representing the desired pathname, and returns a boolean.
From Javadoc of renameTo
..., it might not be atomic, and it
might not succeed if a file with the
destination abstract pathname already
exists.
You check the returned boolean in the second renameTo command. Remove all renameTo commands, or store the boolean of the first command and print this boolean to the console.
First thing, you sometimes use the \ and other times //, im on Mac, so not sure what you should use on Windows.
Second, you are renaming all the files to the same name.
Fix:
boolean renamed = f[i].renameTo(new File("D://CFF1156/changed"+ i + ".txt"));
System.out.println(renamed?"Succesfully renamed":"Error");

Categories

Resources