Having problems adding a cookie to my session - java

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

Related

String line or StringTokenizer with a Reader?

I had a file to read and with this code I succeeded my JUnit tests. As you can see, I pass the String line as parameter to the readPrevisione(...) method.
package oroscopo.persistence;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;
public class TextFileOroscopoRepository implements OroscopoRepository {
private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();
public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
if (baseReader == null)
throw new IllegalArgumentException("baseReader is null");
BufferedReader bufReader = new BufferedReader(baseReader);
String line;
while((line=bufReader.readLine()) != null){
readPrevisione(line,bufReader);
}
}
private void readPrevisione(String line, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = line.trim();
if (!Character.isUpperCase(nomeSettore.charAt(0)))
throw new BadFileFormatException();
List<Previsione> listaPrev = new ArrayList<>();
while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
try{
StringTokenizer st1 = new StringTokenizer(line, "\t");
if(st1.countTokens() < 2)
throw new BadFileFormatException();
String prev = st1.nextToken("\t").trim();
int val = Integer.parseInt(st1.nextToken("\t").trim());
Set<SegnoZodiacale> segni = new HashSet<>();
if (st1.hasMoreTokens()){
while(st1.hasMoreTokens()){
try{
segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
}
catch (IllegalArgumentException e){
throw new BadFileFormatException();
}
}
Previsione p = new Previsione(prev,val,segni);
listaPrev.add(p);
}
else{
Previsione p2 = new Previsione(prev,val);
listaPrev.add(p2);
}
}
catch (NumberFormatException e){
throw new BadFileFormatException();
}
catch (NoSuchElementException e){
throw new BadFileFormatException();
}
}
mapSettore.put(nomeSettore, listaPrev);
}
#Override
public Set<String> getSettori() {
return mapSettore.keySet();
}
#Override
public List<Previsione> getPrevisioni(String settore) {
return mapSettore.get(settore.toUpperCase());
}
}
Here with the same code, instead passing the read line as parameter, I pass the StringTokenizer that already has read the line. It should work like above but my JUnit tests fail. What did I do wrong?
package oroscopo.persistence;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;
public class TextFileOroscopoRepository implements OroscopoRepository {
private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();
public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
if (baseReader == null)
throw new IllegalArgumentException("baseReader is null");
BufferedReader bufReader = new BufferedReader(baseReader);
String line;
while((line=bufReader.readLine()) != null){
StringTokenizer st = new StringTokenizer(line);
readPrevisione(st,bufReader);
}
}
private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = st.nextToken().trim();
if (!Character.isUpperCase(nomeSettore.charAt(0)))
throw new BadFileFormatException();
List<Previsione> listaPrev = new ArrayList<>();
String line;
while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
try{
StringTokenizer st1 = new StringTokenizer(line, "\t");
if(st1.countTokens() < 2)
throw new BadFileFormatException();
String prev = st1.nextToken("\t").trim();
int val = Integer.parseInt(st1.nextToken("\t").trim());
Set<SegnoZodiacale> segni = new HashSet<>();
if (st1.hasMoreTokens()){
while(st1.hasMoreTokens()){
try{
segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
}
catch (IllegalArgumentException e){
throw new BadFileFormatException();
}
}
Previsione p = new Previsione(prev,val,segni);
listaPrev.add(p);
}
else{
Previsione p2 = new Previsione(prev,val);
listaPrev.add(p2);
}
}
catch (NumberFormatException e){
throw new BadFileFormatException();
}
catch (NoSuchElementException e){
throw new BadFileFormatException();
}
}
mapSettore.put(nomeSettore, listaPrev);
}
#Override
public Set<String> getSettori() {
return mapSettore.keySet();
}
#Override
public List<Previsione> getPrevisioni(String settore) {
return mapSettore.get(settore.toUpperCase());
}
}
EDIT: Here is the File.txt that I want to read.
And here is an example of one of my JUnit test:
#Test
public void testLetturaCorrettaPrevisioni1() throws IOException, BadFileFormatException {
Reader mr = new StringReader(
"NOMESEZIONE\navrai la testa un po' altrove\t\t4\tARIETE,TORO,GEMELLI\ngrande intimita'\t9\nFINE\n"
+ "SEZIONE2\ntesto di prova\t\t\t\t\t66\t\nFINE");
OroscopoRepository or = new TextFileOroscopoRepository(mr);
assertEquals("avrai la testa un po' altrove", or.getPrevisioni("nomesezione").get(0).getPrevisione());
assertEquals(4, or.getPrevisioni("nomesezione").get(0).getValore());
Set<SegnoZodiacale> validi = new HashSet<SegnoZodiacale>() {
private static final long serialVersionUID = 1L;
{
add(SegnoZodiacale.ARIETE);
add(SegnoZodiacale.TORO);
add(SegnoZodiacale.GEMELLI);
}
};
for (SegnoZodiacale s : SegnoZodiacale.values()) {
if (validi.contains(s))
assertTrue(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
else
assertFalse(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
}
assertEquals("grande intimita'", or.getPrevisioni("nomesezione").get(1).getPrevisione());
assertEquals(9, or.getPrevisioni("nomesezione").get(1).getValore());
for (SegnoZodiacale s : SegnoZodiacale.values()) {
assertTrue(or.getPrevisioni("nomesezione").get(1).validaPerSegno(s));
}
}
You are creating StringTokenizer with default delimiter, that is, "the space character, the tab character, the newline character, the carriage-return character, and the form-feed character."
So in the first case you set as value of the "nomeSettore" variable the whole line but when you use StringTokenizer.nextToken() you are giving to "nomeSettore" just the value of the first token. So, "nomeSettore" can have different values if your String "line" contains whitespaces and you will have different key-value pairs inside you map.
You can take a look at this example:
public class TestSO {
public static void main(String[] args) {
String line = "abcdfs faf afd fa";
StringTokenizer st = new StringTokenizer(line);
readPrevisione(st, null);
readPrevisione(line, null);
}
private static void readPrevisione(StringTokenizer st, BufferedReader bufReader) {
String nomeSettore = st.nextToken().trim();
System.out.println(nomeSettore);
}
private static void readPrevisione(String st, BufferedReader bufReader) {
String nomeSettore = st.trim();
System.out.println(nomeSettore);
}
}
It prints as output:
abcdfs
abcdfs faf afd fa
I've understood why it didn't work..
The String line was : "EXAMPLE\n"
but after
while((line=bufReader.readLine()) != null){
...}
line = "EXAMPLE" because the readLine() eats the newline.
So I passed to the readPrevisione() a StringTokenizer as parameter
while((line=bufReader.readLine()) != null){
StringTokenizer st = new StringTokenizer(line);
readPrevisione(st,bufReader);
}
private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = st.nextToken().trim();
...}
And st.nextToken() search for a \n that is not contained in "EXAMPLE". That's why it didn't work.

How can I take rows to the TXT file in the method?

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

Search for a string in html file using Jsoup

Can anyone help me with searching for a particular string in HTML file using Jsoup or any other method. There are inbuilt methods but they help in extracting title or script texts inside a specific tags and not string in general.
In this code I have used one such inbuilt method to extract title from the html page.
But I want to search a string instead.
package dynamic_tester;
import java.io.File;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class tester {
public static void main(String args[])
{
Document htmlFile = null;
{
try {
htmlFile = Jsoup.parse(new File("x.html"), "ISO-8859-1");
}
catch (IOException e)
{
e.printStackTrace();
}
String title = htmlFile.title();
System.out.println("Title = "+title);
}
}
}
Here's a sample. It reads the HTML file as text String and then performs search on that String.
package com.example;
import java.io.FileInputStream;
import java.nio.charset.Charset;
public class SearchTest {
public static void main(String[] args) throws Exception {
StringBuffer htmlStr = getStringFromFile("test.html", "ISO-8859-1");
boolean isPresent = htmlStr.indexOf("hello") != -1;
System.out.println("is Present ? : " + isPresent);
}
private static StringBuffer getStringFromFile(String fileName, String charSetOfFile) {
StringBuffer strBuffer = new StringBuffer();
try(FileInputStream fis = new FileInputStream(fileName)) {
byte[] buffer = new byte[10240]; //10K buffer;
int readLen = -1;
while( (readLen = fis.read(buffer)) != -1) {
strBuffer.append( new String(buffer, 0, readLen, Charset.forName(charSetOfFile)));
}
} catch(Exception ex) {
ex.printStackTrace();
strBuffer = new StringBuffer();
}
return strBuffer;
}
}

The system cannot find the path specified in java

Working on Selenium Webdriver and using Java. I'm getting error as The system cannot find the path specified
Code:
package test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class OEPR_DefaultTab{
private static Logger Log = Logger.getLogger(OEPR_DefaultTab.class.getName());
private WebDriver driver;
private StringBuffer verificationErrors = new StringBuffer();
Properties p= new Properties();
public Selenium selenium;
#BeforeTest
public void Login() throws Exception {
driver = new FirefoxDriver();
try {
p.load(new FileInputStream("C:/Login.txt"));
} catch (Exception e) {
e.getMessage();
}
String url=p.getProperty("url");
DOMConfigurator.configure("src/log4j.xml");
Log.info("______________________________________________________________");
Log.info("Initializing Selenium...");
selenium = new DefaultSelenium("localhost", 4444, "*firefox",url);
Thread.sleep(5000);
Log.info("Selenium instance started");
try {
p.load(new FileInputStream("C:/Login.txt"));
} catch (Exception e) {
e.getMessage();
}
Log.info("Accessing Stored uid,pwd from the stored text file");
String uid=p.getProperty("loginUsername");
String pwd=p.getProperty("loginPassword");
Log.info("Retrieved uid pwd from the text file");
try
{
driver.get("https://10.4.16.159/login");
}
catch(Exception e)
{
Reporter.log("network server is slow..check internet connection");
Log.info("Unable to open the website");
throw new Error("network server is slow..check internet connection");
}
performLogin(uid,pwd);
}
public void performLogin(String uid,String pwd) throws Exception
{
Log.info("Sign in to the OneReports website");
Thread.sleep(5000);
Log.info("Enter Username");
driver.findElement(By.id("loginUsername")).sendKeys(uid);
Log.info("Enter Password");
driver.findElement(By.id("loginPassword")).sendKeys(pwd);
//submit
Log.info("Submitting login details");
waitforElement(driver,120 , "//*[#id='submit']");
driver.findElement(By.id("submit")).submit();
Thread.sleep(6000);
Actions actions = new Actions(driver);
Log.info("Clicking on Reports link");
if(existsElement("reports")==true){
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
Log.info("Clicking on Extranet link");
if(existsElement("extranet")==true){
WebElement menuHoverLink = driver.findElement(By.id("extranet"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
Log.info("Clicking on PR link");
if(existsElement("ext-pr")==true){
WebElement menuHoverLink = driver.findElement(By.id("ext-pr"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
Log.info("Clicking on Overview and Evolution PR link");
if(existsElement("ext-pr-backlog-evolution")==true){
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", driver.findElement(By.id("ext-pr-backlog-evolution") ));
//executor.executeScript("document.getElementById('ext-pr-backlog-evolution').style.display='block';");
//driver.findElement(By.id("ext-pr-backlog-evolution")).click();
// WebElement menuHoverLink = driver.findElement(By.id("ext-pr-backlog-evolution"));
//actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
}
//Filter selection-1
#Test()
public void Filterselection_1() throws Exception{
BufferedReader in = new BufferedReader(new FileReader("C:/FilerSection/visualization.txt"));\\ Here i'm getting error
String line;
line = in.readLine();
in.close();
String[] expectedDropDownItemsInArray = line.split("=")[1].split(",");
// Create expected list :: This will contain expected drop-down values
ArrayList<String> expectedDropDownItems = new ArrayList<String>();
for(int i=0; i<expectedDropDownItemsInArray.length; i++)
expectedDropDownItems.add(expectedDropDownItemsInArray[i]);
// Create a webelement for the drop-down
WebElement visualizationDropDownElement = driver.findElement(By.id("visualizationId"));
// Instantiate Select class with the drop-down webelement
Select visualizationDropDown = new Select(visualizationDropDownElement);
// Retrieve all drop-down values and store in actual list
List<WebElement> valuesUnderVisualizationDropDown = visualizationDropDown.getOptions();
ArrayList<String> actualDropDownItems = new ArrayList<String>();
for(WebElement value : valuesUnderVisualizationDropDown){
actualDropDownItems.add(value.getText());
}
// Compare expected and actual list
for (int i = 0; i < actualDropDownItems.size(); i++) {
if (!expectedDropDownItems.get(i).equals(actualDropDownItems.get(i)))
System.out.println("Drop-down values are NOT in correct order");
}
}
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (Exception e) {
System.out.println("id is not present ");
return false;
}
return true;
}
private void waitforElement(WebDriver driver2, int i, String string) {
// TODO Auto-generated method stub
}
#AfterTest
public void tearDown() throws Exception {
Log.info("Stopping Selenium...");
Log.info("______________________________________________________________");
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
Assert.fail(verificationErrorString);
}
}
}
Please check the code give me some solution.
The scenario which is present in the How to compare the drop down options is matching with the UI options in Selenium WebDriver?
For this scenario I'm trying to script. Please check the link as well.
If that's the exact text you are seeing this typically isn't a code issue - it means you need to update your PATH environment variable with the directory where java was installed.
Replace
BufferedReader in = new BufferedReader(new FileReader("C:/FilerSection/visualization.txt"));
with
BufferedReader in = new BufferedReader(new FileReader("C:\\FilerSection\\visualization.txt"));
This should help.

Remove Duplicate Lines from Text using Java

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

Categories

Resources