How can I print the line in the txt file drawn in the void txt() method, inside the driver.get() parentheses in void link() with quotes?
I want to get a link from the txt file and let the automatic program enter the site.
Thanks for your help.
package test2;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class test2 {
public WebDriver driver = new ChromeDriver();
public Actions action = new Actions(driver);
public static String rows = "";
public void link() throws InterruptedException {
// driver.get("https://www.google.com/");
//How can I type here,taken row from the TXT file in the quotes("")?
driver.get(rows);
Thread.sleep(3000);
}
public void txt() throws IOException {
// open the LinkAl txt file
File file = new File("LinkAl.txt");
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
int i=0;
rows = reader.readLine();
while (rows!=null) {
i++;
// Get the second row to the LinkAl txt file
if(i==2)
{
System.out.println(rows);
}
rows = reader.readLine();
}
}
public void driverquit() {
driver.quit();
}
public static void main(String[] args) throws InterruptedException, IOException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
test2 Links = new test2();
// Links.link();
Links.txt();
Links.driverquit();
}
}
Change your below method like mentioned to read file line by line till EOF.
public void txt() throws IOException {
// open the LinkAl txt file
File file = new File("LinkAl.txt");
String line="";
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
// System.out.println(line);
link(line);
}
}
Also if you want to pass the read line to link method change it as below
public void link(String line) throws InterruptedException {
System.out.println("Dosyadançekilenlerveriler: " + line);
// driver.get("https://www.google.com/");
driver.get(line);
Thread.sleep(3000);
}
Related
The code should do a reverse and output the result to out.txt, but this does not happen, can you explain my mistake in the code. Thanks in advance
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
builder.reverse();
while ((sb.read()) != -1) {
output.write(String.valueOf(builder.reverse()));
}
}
}
}
}
You are trying to reverse the string twice because of that the string is getting back to the original string. Also, there is an unnecessary (as per my understanding) while loop inside the for loop (I have removed that in my answer).
Try the below code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
// above statement can be replaced with
// String[] words = data.split(" {34}");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
// why while loop is required?
//while ((sb.read()) != -1) {
output.write(builder.reverse().toString());
output.flush(); // flush data to the file
//}
}
}
output.close();
}
}
Read about File writer here on how to flush data and also close the writer after writing is completed.
So basically; I found these 2 classes for creating a cookie and adding it to a session from some website because I don't know anything about cookies. I deleted some things from the code like "isSecured" because I thought it's unnecessary.
Creating the cookie is no problem but adding it to the session doesn't work, hopefully not due to the parts I deleted... But I really think they are unimportant.
Here is my whole class:
package indeed;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Cookies {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = 0;
System.out.print("input 1 for readCookie or 2 for writeCookie: ");
input = sc.nextInt();
switch (input) {
case 1:
readCookie();
break;
case 2:
writeCooke();
break;
default:
System.out.println("no");
break;
}
}
public static void readCookie() {
WebDriver driver;
System.setProperty("webdriver.gecko.driver", "C:\\geckodriver.exe");
driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get("https://secure.indeed.com/account/login?hl=de&continue=%2Faccount%2Fview%3Fhl%3Dde");
// Input Email id and Password If you are already Register
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login-email-input"))).sendKeys("example#email.com");
driver.findElement(By.id("login-password-input")).sendKeys("examplepass");
driver.findElement(By.id("login-submit-button")).click();
// create file named Cookies to store Login Information
File file = new File("Cookies.data");
try {
// Delete old file if exists
file.delete();
file.createNewFile();
FileWriter fileWrite = new FileWriter(file);
BufferedWriter Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
// loop for getting the cookie information
for (Cookie ck : driver.manage().getCookies()) {
Bwrite.write((ck.getName() + ";" + ck.getValue()));
Bwrite.newLine();
}
Bwrite.close();
fileWrite.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void writeCooke() {
WebDriver driver;
System.setProperty("webdriver.gecko.driver", "C:\\geckodriver.exe");
driver = new FirefoxDriver();
try {
File file = new File("Cookies.data");
FileReader fileReader = new FileReader(file);
BufferedReader Buffreader = new BufferedReader(fileReader);
String strline;
while ((strline = Buffreader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(strline, ";");
while (token.hasMoreTokens()) {
String name = token.nextToken();
String value = token.nextToken();
String domain = token.nextToken();
Cookie ck = new Cookie(name, value, domain);
System.out.println(ck);
driver.manage().addCookie(ck); // This will add the stored cookie to your current session
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
driver.get("https://secure.indeed.com/account/login?hl=de&continue=%2Faccount%2Fview%3Fhl%3Dde");
}
}
So I solved this particular problem myself by NOT using cookies but instead using the same instance of webdriver to avoid needing cookies in the first place
public static void switchToNewTab() {
openNewTab();
String subWindowHandler = null;
Set<String> handles = getDriver().getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()) {
subWindowHandler = iterator.next();
}
getDriver().switchTo().window(subWindowHandler);
}
public static void openNewTab() {
((JavascriptExecutor) getDriver()).executeScript("window.open('about:blank','_blank');");
}
public static void firstRunWebpage() {
getDriver().get("https://employers.indeed.com/p#post-job");
getWait().until(ExpectedConditions.visibilityOfElementLocated(By.id("login-email-input"))).sendKeys("example#email.com");
getDriver().findElement(By.id("login-password-input")).sendKeys("examplepass");
//getDriver().findElement(By.xpath("//*[#id=\"label-login-rememberme-checkbox\"]")).click(); //typically already checked
getDriver().findElement(By.id("login-submit-button")).click();
}
public static void afterFirstRun() {
switchToNewTab();
getDriver().get("https://employers.indeed.com/p#post-job");
}
I was trying to parse text from a textfile , then split it in words. However when split takes the words, it doesn't recognize a new line as a space ?
Sometimes it recognize a space on the next line but not if there are two new lines before the words continue.
I put a space on each new line to avoid it.
Is this a normal behavior, and how to avoid it ?
Using e.g a textfile with : this is a test "enter" for checking "enter-enter" something "enter" in this text (typing enter as writed)
package textparseproblem;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
public class TextParseProblem {
JFileChooser chooser = new JFileChooser();
File f;
String so = "";
public static void main(String[] args) throws InterruptedException, Exception {
new TextParseProblem().openFchooser();
}
private void openFchooser() throws FileNotFoundException, IOException, InterruptedException, Exception {
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
f = chooser.getSelectedFile();
} loadFile(f);
}
private void loadFile(File fileC) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
while (true) {
String s = reader.readLine();
if (s == null) break;
so += s;
}
} parseMethod();
}
private void parseMethod() {
String[] sa1 = so.split("\\s");
for(String soo : sa1) {
System.out.println(soo);
}
}
}
According to your strategy, one of the way is to add additional "space" between strings (read lines), so you can later recognize them:
private void loadFile(File fileC) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
while (true) {
String s = reader.readLine();
if (s == null) {
break;
}
so += " "+s; // here
}
}
parseMethod();
}
If in the case your string has that additional "space" you can parse it when you will correct this method:
private void parseMethod() {
String[] sa1 = so.split("\\s+"); // to recognize some spaces
for (String soo : sa1) {
System.out.println(soo);
}
}
Other methods don't need changes
I have 3 methods
for open file
for read file
for return things read in method read
this my code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication56;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author x
*/
public class RemoteFileObjectImpl extends java.rmi.server.UnicastRemoteObject implements RemoteFileObject
{
public RemoteFileObjectImpl() throws java.rmi.RemoteException {
super();
}
File f = null;
FileReader r = null;
BufferedReader bfr = null;
String output = "";
public void open(String fileName) {
//To read file passWord
f = new File(fileName);
}
public String readLine() {
try {
String temp = "";
String newLine = System.getProperty("line.separator");
r = new FileReader(f);
while ((temp = bfr.readLine()) != null) {
output += temp + newLine;
bfr.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return output;
}
public void close() {
try {
bfr.close();
} catch (IOException ex) {
}
}
public static void main(String[]args) throws RemoteException{
RemoteFileObjectImpl m = new RemoteFileObjectImpl();
m.open("C:\\Users\\x\\Documents\\txt.txt");
m.readLine();
m.close();
}
}
But it does not work.
What do you expect it to do, you are not doing anything with the line you read, just
m.readLine();
Instead:
String result = m.readLine();
or use the output variable that you saved.
Do you want to save it to a variable, print it, write it to another file?
Update: after your update in the comments:
Your variable bfr is never created/initialized. You are only doing this:
r = new FileReader(f);
so bfr is still null.
You should do something like this instead:
bfr = new BufferedReader(new FileReader(f));
I was wondering if anyone has logic in java that removes duplicate lines while maintaining the lines order.
I would prefer no regex solution.
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
if (lines.add(uniqueLine = super.readLine()))
return uniqueLine;
return "";
}
//for testing..
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
if (strLine != "")
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Modified Version:
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"/home/emil/Desktop/ff.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
If you feed the lines into a LinkedHashSet, it ignores the repeated ones, since it's a set, but preserves the order, since it's linked. If you just want to know whether you've seena given line before, feed them into a simple Set as you go on, and ignore those which the Set already contains/contained.
It can be easy to remove duplicate line from text or File using new java Stream API. Stream support different aggregate feature like sort,distinct and work with different java's existing data structures and their methods. Following example can use to remove duplicate or sort the content in File using Stream API
package removeword;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
import static java.nio.file.StandardOpenOption.*;
import static java.util.stream.Collectors.joining;
public class Java8UniqueWords {
public static void main(String[] args) throws IOException {
Path sourcePath = Paths.get("C:/Users/source.txt");
Path changedPath = Paths.get("C:/Users/removedDouplicate_file.txt");
try (final Stream<String> lines = Files.lines(sourcePath )
// .map(line -> line.toLowerCase()) /*optional to use existing string methods*/
.distinct()
// .sorted()) /*aggregrate function to sort disctincted line*/
{
final String uniqueWords = lines.collect(joining("\n"));
System.out.println("Final Output:" + uniqueWords);
Files.write(changedPath , uniqueWords.getBytes(),WRITE, TRUNCATE_EXISTING);
}
}
}
Read the text file using a BufferedReader and store it in a LinkedHashSet. Print it back out.
Here's an example:
public class DuplicateRemover {
public String stripDuplicates(String aHunk) {
StringBuilder result = new StringBuilder();
Set<String> uniqueLines = new LinkedHashSet<String>();
String[] chunks = aHunk.split("\n");
uniqueLines.addAll(Arrays.asList(chunks));
for (String chunk : uniqueLines) {
result.append(chunk).append("\n");
}
return result.toString();
}
}
Here's some unit tests to verify ( ignore my evil copy-paste ;) ):
import org.junit.Test;
import static org.junit.Assert.*;
public class DuplicateRemoverTest {
#Test
public void removesDuplicateLines() {
String input = "a\nb\nc\nb\nd\n";
String expected = "a\nb\nc\nd\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
#Test
public void removesDuplicateLinesUnalphabetized() {
String input = "z\nb\nc\nb\nz\n";
String expected = "z\nb\nc\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
}
Here's another solution. Let's just use UNIX!
cat MyFile.java | uniq > MyFile.java
Edit: Oh wait, I re-read the topic. Is this a legal solution since I managed to be language agnostic?
For better/optimum performance, it's wise to use Java 8's API features viz. Streams & Method references with LinkedHashSet for Collection as below:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
public class UniqueOperation {
private static PrintWriter pw;
enter code here
public static void main(String[] args) throws IOException {
pw = new PrintWriter("abc.txt");
for(String p : Files.newBufferedReader(Paths.get("C:/Users/as00465129/Desktop/FrontEndUdemyLinks.txt")).
lines().
collect(Collectors.toCollection(LinkedHashSet::new)))
pw.println(p);
pw.flush();
pw.close();
System.out.println("File operation performed successfully");
}
here I'm using a hashset to store seen lines
Scanner scan;//input
Set<String> lines = new HashSet<String>();
StringBuilder strb = new StringBuilder();
while(scan.hasNextLine()){
String line = scan.nextLine();
if(lines.add(line)) strb.append(line);
}