Reading text file in Seleniumwebdriver - java

I want to read values from a text file using selenium webdriver. I want to get third text from the text file. The text file is something like this.
1.Apple
2.Orange
3.Grape
I want to read the third option(Grape) and to display it. Please help

If you are able to read the text file and store data in a String , then you can use some regular expression to get the third option.
String ps = ".*3.([A-Za-z]*)"; // regex
String s = "1.Apple 2.Orange 3.Grape"; // file data in a String object
Pattern p = Pattern.compile(ps);
Matcher m = p.matcher(s);
if (m.find()){
System.out.println(m.group(0)); // returns value of s
System.out.println(m.group(1)); // returns result= Grape
}
Check regex here : https://regex101.com/r/cF9pB7/1
You can get some other values by changing the regulaar

You do not need selenium to text file. Selenium is just a browser automation tool. You can use below code to read text file using Java.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You can integrate it with your selenium code.

Related

Is there any in built function in Java to remove unwanted data from extracted data

I extracted some text from a text file but now I want only some specific words from that text.
What I have tried is read from that text file and I have searched by using keyword:
FileReader fr = new
FileReader("D:\\PDFTOEXCEL\\Extractionfrompdf.txt");
BufferedReader br = new BufferedReader(fr);
String s;
String keyword = "dba COPIEFacture ";
while ((s = br.readLine()) != null) {
if (s.contains(keyword)) {
System.out.println(s);
I got Output like this: dba COPIEFacture du 28/05/2018 n° 10077586115Récapitulatif de vote facture
But I want only 28/05/2018 This so please help me
You'll need to use String manipulation methods.
It's difficult to know the best way to do it without seeing other outputs, but you could probably use split() and indexOf() to retrieve the date.
There are other, probably more complex, methods. For example, here's a StackOverflow answer about retrieving dates from strings using a regex pattern.
This will do the trick.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
FileReader fr;
String keyword = "dba COPIEFacture du ";
String textToFind = "28/05/2018"; // The length usually will not
// change.You can use value
// 10(length) instead
StringBuilder sb = new StringBuilder();
try {
fr = new FileReader("D:\\PDFTOEXCEL\\Extractionfrompdf.txt");
int i;
while ((i = fr.read()) != -1) {
sb.append((char) i);
}
int start = sb.indexOf(keyword) + keyword.length();
int end = start + textToFind.length();
System.out.print(sb.substring(start, end)); //output: 28/05/2018
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java - Groovy : regex parse text block

I know that this is a common question and I've been through a lot of forums to figure out whats the problem in my code.
I have to read a text file with several blocks in the following format:
import com.myCompanyExample.gui.Layout
/*some comments here*/
#Layout
LayoutModel currentState() {
MyBuilder builder = new MyBuilder()
form example
title form{
row_1
row_1
row_n
}
return build.get()
}
#Layout
LayoutModel otherState() {
....
....
return build.get()
}
I have this code to read all the file and I'd like to extract each block between the keyword "#Layout" and the keyword "return". I need also to catch all newline so later I'll be able to split each matched block into a list
private void myReadFile(File fileLayout){
String line = null;
StringBuilder allText = new StringBuilder();
try{
FileReader fileReader = new FileReader(fileLayout);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
allText.append(line)
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file");
}
catch(IOException ex) {
System.out.println("Error reading file");
}
Pattern pattern = Pattern.compile("(?s)#Layout.*?return",Pattern.DOTALL);
Matcher matcher = pattern.matcher(allText);
while(matcher.find()){
String [] layoutBlock = (matcher.group()).split("\\r?\\n")
for(index in layoutBlock){
//check each line of the current block
}
}
layoutBlock returns size=1
I think this can potentially be a so called XY problem anyway...if the groovy source is composed only by #Layout annotated blocks of code you can use a tempered greedy token to select till the next annotation (view online demo).
Change the pattern loc as this:
Pattern pattern = Pattern.compile( "#Layout(?:(?!#Layout).)*", Pattern.DOTALL );
PS: the dotall flag (?s) inside the regex and the parameter Pattern.DOTALL do the same thing (enable the so called multiline mode), use only one of them indifferently.
UPDATE
I tried your code, the problem (preserving newline) is in the method you use to slurp the file (bufferedReader.readline() remove the newline at the end of the string).
Simply readd a newline when append to allText:
String ln = System.lineSeparator();
while((line = bufferedReader.readLine()) != null) {
allText.append(line + ln);
}
Or you can replace all the code to slurp the file with this:
import java.nio.file.Files;
import java.nio.file.Paths;
//can throw an IOException
String filePath = "/path/to/layout.groovy";
String allText = new String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);

How do I read Windows NTFS's Alternate Data Stream using Java's IO?

I'm trying to have my Java application read all the data in a given path. So files, directories, metadata etc. This also includes one weird thing NTFS has called Alternate Data Stream (ADS).
Apparently it's like a second layer of data in a directory or file. You can open the command prompt and create a file in the ADS using ':', for example:
C:\ADSTest> echo test>:ads.txt
So,
C:\ADSTest> notepad :ads.txt
Should open a notepad that contains the string "test" in it. However, if you did:
C:\ADSTest> dir
You will not be able to see ads.txt. However, if you use the dir option that displays ADS data, you will be able to see it:
C:\ADSTest> dir /r
MM/dd/yyyy hh:mm .:ads.txt
Now, I am aware that Java IO has the capability to read ADS. How do I know that? Well, Oracle's documentations clearly states so:
If the file attributes supported by your file system implementation
aren't sufficient for your needs, you can use the
UserDefinedAttributeView to create and track your own file attributes.
Some implementations map this concept to features like NTFS
Alternative Data Streams and extended attributes on file systems such
as ext3 and ZFS.
Also, a random post on a random forum :D
The data is stored in NTFS Alternate data streams (ADS) which are
readable through Java IO (I have tested it).
The problem is, I can't find any pre-written file attribute viewer that can parse ADS, and I don't understand how to write an ADS parser of my own. I'm a beginner programmer so I feel this is way over my head. Would anybody please help me out or point me in the right direction?
Solution
EDIT: With the help of #knosrtum I was able to concoct a method that will return all the parsed ADS information from a given path as an ArrayList of Strings (it can also be easily edited to an ArrayList of files). Here's the code for anyone who might need it:
public class ADSReader {
public static ArrayList<String> start(Path toParse) {
String path = toParse.toString();
ArrayList<String> parsedADS = new ArrayList<>();
final String command = "cmd.exe /c dir " + path + " /r"; // listing of given Path.
final Pattern pattern = Pattern.compile(
"\\s*" // any amount of whitespace
+ "[0123456789,]+\\s*" // digits (with possible comma), whitespace
+ "([^:]+:" // group 1 = file name, then colon,
+ "[^:]+:" // then ADS, then colon,
+ ".+)"); // then everything else.
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
parsedADS.add((matcher.group(1)));
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int z = 0; z<parsedADS.size(); z++)
System.out.println(parsedADS.get(z));
return parsedADS;
}
}
I was able to read the ADS of a file simply by opening the the file with the syntax "file_name:stream_name". So if you've done this:
C:>echo Hidden text > test.txt:hidden
Then you should be able to do this:
package net.snortum.play;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class AdsPlay {
public static void main(String[] args) {
new AdsPlay().start();
}
private void start() {
File file = new File("test.txt:hidden");
try (BufferedReader bf = new BufferedReader( new FileReader(file))) {
String hidden = bf.readLine();
System.out.println(hidden);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you want to get the ADS data from the dir /r command, I think you just need to execute a shell and capture the output:
package net.snortum.play;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExecPlay {
public static void main(String[] args) {
new ExecPlay().start();
}
private void start() {
String fileName = "not found";
String ads = "not found";
final String command = "cmd.exe /c dir /r"; // listing of current directory
final Pattern pattern = Pattern.compile(
"\\s*" // any amount of whitespace
+ "[0123456789,]+\\s*" // digits (with possible comma), whitespace
+ "([^:]+):" // group 1 = file name, then colon
+ "([^:]+):" // group 2 = ADS, then colon
+ ".+"); // everything else
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
fileName = matcher.group(1);
ads = matcher.group(2);
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(fileName + ", " + ads);
}
}
Now you can use the first code listing to print the ADS data.

how to use escape characters for patterns read from file in java

I am reading some patterns from a file and using it in String matches method. but while reading the patterns from the file, the escape characters are not working
Ex I have few data ex "abc.1", "abcd.1", "abce.1", "def.2"
I want do do some activity if the string matches "abc.1" i.e abc. followed by any characters or numbers
I have a file that stores the pattern to be matched ex the pattern abc\..*
but when I read the pattern from the file and using it in String matches method it does not work.
any suggestions
a sample java program to demonstrate the issue is :
package com.test.resync;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class TestPattern {
public static void main(String args[]) {
// raw data against which the pattern is to be matched
String[] data = { "abc.1", "abcd.1", "abce.1", "def.2" };
String regex_data = ""; // variable to hold the regexpattern after
// reading from the file
// regex.txt the file containing the regex pattern
File file = new File(
"/home/ekhaavi/Documents/WORKSPACE/TESTproj/src/com/test/regex.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String str = "";
while ((str = br.readLine()) != null) {
if (str.startsWith("matchedpattern")) {
regex_data = str.split("=")[1].toString(); // setting the
// regex pattern
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*if the regex is set by the below String literal it works fine*/
//regex_data = "abc\\..*";
for (String st : data) {
if (st.matches(regex_data)) {
System.out.println(" data matched "); // this is not printed when the pattern is read from the file instead of setting it through literals
}
}
}
}
The regex.txt file has the below entry
matchedpattern=abc\..*
Use Pattern.quote(String) method:
if (st.matches(Pattern.quote(regex_data))) {
System.out.println(" data matched "); // this is not printed when the pattern is read from the file instead of setting it through literals
}
There are some other issues that you should consider resolving:
You're overwriting the value of regex_data in the while loop. Did you intend to store all the the regex pattern in a list?
String#split()[0] will return a String only. You don't need to invoke toString() on that.

Need help reading files

I'm writing a mock stock market in Java, and I want the ability for the user to view stocks purchased. I decided the easiest way to do this is to write to a file. My problem is that every time I run this program and attempt to read from the file, it outputs the path it took to read it. The information I want is correctly written to the file, but it isn't reading from it the way I want.
Here is the code I used for the file reading section:
if (amountOfStocks1 >= 1) {
Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");
while (stocksBought1.hasNext()) {
String fileRead = stocksBought1.nextLine();
System.out.println(fileRead);
}
stocksBought1.close();
runMenu = 1;
}
There are 7 of these amountOfStocks if/else statements.
I'm not sure if that's enough information. If it's not, tell me what to put on, and I'll do that.
If you can help me fix this problem or if you know an easier way to read and write to files that would be great!
Instead of:
Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");
Try:
Scanner stocksBought1 = new Scanner(new File("stocksbought/stocksBought1.txt"));
When you only pass a String to the Scanner constructor the Scanner just scans that String. If you give it a File it will scan the contents of the File.
You would probably be better off using the FileReader object. You would use code similar to the following:
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
In addition, you can use the FileWriter object to write to a file. There's lots of examples on the internet. Easy to find on simple Google search. Hope this helps.
Use FileReader.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Categories

Resources