How to pass parameter to data provider in testng from csv file - java

Am reading data from csv file , i have test for which this data will be the input .
i want it to run as tescase for every set of value. for that am using data provider
The problem is , it is taking only the last set row of data , please help me in debugging the code
For eg : if my csv has following data
name1 id1 text1
name2 id2 text2
name3 id3 text3
it taking only last row name3 id3 text3 and running the test only once not three times.
#DataProvider(name = "test")
public Object[][] provider( ) throws InterruptedException
{
Object[][] returnObject ;
String[] checkpoint = ReadfromCSV();
count = count + 1;
returnObject = new Object[][]{checkpoint };
return returnObject;
}
#Test(description = "Test", groups = "test" , dataProvider = "test")
public void compare(String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11 ) {
System.out.println("1:" + val1);
System.out.println("4:" + val2);
System.out.println("5:" + val3);
}
#SuppressWarnings("null")
public String[] ReadfromCSV() throws InterruptedException {
String[] data= null;
String csvFile = "F:/sample1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return data;
}

You should read entire file in data provider and return iterator of test cases. Here is some pseudocode for data provider. Notice that I used List<String []> to store test cases instead of Object[][]. This allows you do define test cases dynamically.
#DataProvider(name = "test")
public Iterator<Object []> provider( ) throws InterruptedException
{
List<Object []> testCases = new ArrayList<>();
String[] data= null;
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
testCases.add(data);
}
return testCases.iterator();
}

public String[][] ReadfromCSV() throws InterruptedException {
int count =0;
String[] data= null;
String returnObj[][] = null;
//System.out.println(System.getProperty("user.dir"));
String csvFile = System.getProperty("user.dir")+ "/src/test/resources/testdata.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<String> content = new ArrayList<String>();
try {
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
int datalength = 0;
int listsize =0;;
while ((line = br.readLine()) != null) {
// use comma as separator
content.add(line);
}
System.out.println(content);
listsize = content.size();
datalength = content.get(0).split(cvsSplitBy).length;
returnObj = new String[listsize][datalength];
for (int i = 0; i<listsize; i++) {
data = content.get(i).split(cvsSplitBy);
for (int j=0; j< datalength ; j++) {
returnObj[i][j] = data[j];
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return returnObj;
}}

Related

Java - parse CSV into Arrays based on columns

I would like to ask for help with this task:
I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by Java to Arrays / Array lists by columns / headers -> for example
ArrayList column1 = [123,456]
ArrayList column2 = [xyz,zyx]
ArrayList column3 = [321,654]
Thanks everyone.
This is how I would have done this..., note the metod to put the columns in another List for less code and to be more dynamic.
public static void main(String[] args) {
ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("testing.cvs"));
while ((sCurrentLine = br.readLine()) != null) {
String[] fields = sCurrentLine.split("\\$");
for (int i = 0; i < fields.length; i++) {
if (columns.size()<=i){
columns.add(new ArrayList<String>());
}
columns.get(i).add(fields[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I thin this can help you to fix the problem just tery it.
public static void main(String[] args) {
Scanner s = null;
try {
s = new Scanner(new File("C:\\temp\\file.txt"));
ArrayList lis1 = new ArrayList();
ArrayList lis2 = new ArrayList();
ArrayList lis3 = new ArrayList();
while (s.hasNext()) {
String d = s.nextLine();
lis1.add(d.split("\\$")[0]);
lis2.add(d.split("\\$")[1]);
lis3.add(d.split("\\$")[2]);
}
for (Object l : lis1) {
System.out.print(l+" ");
}
System.out.print("\n ");
for (Object l : lis2) {
System.out.print(l+" ");
}
System.out.print("\n ");
for (Object l : lis3) {
System.out.print(l+" ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
you can use the result when you wont

Reading into a string from a file, but any text after space on a line removed?

I have a large text file with phrases such as:
citybred JJ
Brestowe NNP
STARS NNP NNS
negative JJ NN
investors NNS NNPS
mountain NN
My objective is to keep the first word of each line, without the spaces, and also make them lowercase.
EX:
citybred
brestowe
stars
negative
investors
mountain
Would be returned if the above text was evaluated.
Any help?
Current code:
public class FileLinkList
{
public static void main(String args[])throws IOException{
String content = new String();
File file = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
} catch(FileNotFoundException fnf){
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
Collections.reverse(list);
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.print("Node " + (count++) + " : ");
System.out.println(i.next());
}
}
}
If your token and its POS tag is separated by space :
public class FileLinkList{
public static void main(String[] args) {
BufferedReader br = null;
LinkedList<String> list = new LinkedList<String>();
String word;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("LEXICON.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
word = sCurrentLine.trim().split(" ")[0];
list.add(word.toLowerCase());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Add the following:
content = sc.nextLine();
string[] tokens = content.split(new char[] {' '}, StringSplitOptions.RemovEemptyEntries);
// You can add some validations here...
string word = tokens[0].ToLowerCase();
Try this :
public class FileLinkList {
public static void main(String args[])throws IOException{
String content = new String();
int count=1;
File file = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
if (content != null && content.length() > 0)) {
list.add(content.trim().split(" ")[0].toLowerCase());
}
}
sc.close();
} catch(FileNotFoundException fnf){
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
for (String listItem : list) {
System.out.println(listItem);
}
}
}
With Apache Commons IO it is much simpler to read a file into a list of Strings.
import org.apache.commons.io.FileUtils;
List<String> lines = FileUtils.readLines(new File("abc.txt"));
List<String firstWords = new ArrayList<>();
for (String line : lines) {
String firstWord = line.split(" ")[0].toLowerCase();
firstWords.add(firstWord);
}

Reverse Java full document

I used reverse a string, but now need the final document is the principle, and vice versa:
Hello
Bye
to
Bye
hello
and not:
olleH
eyB
As I do this?
This is my source:
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
String s;
try {
while ((s = br.readLine()) != null) {
StringBuilder reverse = new StringBuilder(s);
String sCadenaInvertida = reverse.reverse().toString();
System.out.println(sCadenaInvertida);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Thanks!!
Just put everything in an ArrayList and use Collections.reverse
http://www.java2s.com/Code/Java/Collections-Data-Structure/ReverseorderofallelementsofJavaArrayList.htm
pseudo code:
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("Bye");
Collections.reverse(arrayList);
System.out.println(arrayList);
Add the items to an array (first come first serve) then traverse the array in reverse
for (into I = array.length; i >= 0; i--) {
//print array[i]
}
Alternatively you can use an ArrayList if you don't know the number of lines in the document
ArrayList<String> theWords= new ArrayList<String>();
while ((s = br.readLine()) != null) {
//split line into words
String[] parts = s.split("\\s+"):
//for each word append to arraylist
for(String s : parts)
{
theWords.append(s);
} //end for loop
} //end while loop
// iterate array, from size-1 to 0
int theWordsSize = theWords.size()--;
for(int i= theWordsSize; i >= 0; i--)
{
System.out.println(theWords.get(i));
} //end for loop
here the answer, It was easy:
public class Reverse2 {
public static void main(String[] args) {
if(args.length != 1){
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
ArrayList<String> lista = new ArrayList<String>();
String s;
try {
while((s=br.readLine()) != null){
lista.add(s);
}
for(int i= lista.size()-1;i>=0;i--){
System.out.println(lista.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
thanks for all the possible solutions

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

delete text file java doesn't work

Here's example:
public static void main (String[] args){
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
String temppath = "C:\\Users\\Charbel\\Desktop\\temp.txt";
File file = new File(path);
File tempfile = new File(temppath);
int numl = search("x");
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(temppath));
while (( line = bf.readLine()) != null)
{
if(countL != numl){
bw.write(line);
bw.newLine();
}
countL++;
}
bf.close();
bw.close();
file.delete();
boolean successful = tempfile.renameTo(file);
System.out.println(successful);
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
public static int search(String name)
{
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
return -1;
}
}
Hello there .. i am trying to read the line of a specific string in a text file , get the number of its line , then copy all the data in the file to another text file except the line of the string
the code is sometimes working 100% and sometimes no ; I go to my desktop I see both files the temp and the original one without deleting and renaming it
i think i have a problem in deleting the file what do you think coders ?
Because when the search method find name(actually "x"),don't reach the line bf.close(), so bf is still opened and file.delete() fails.
So, you need to modify the search method to the below:
public static int search(String name) {
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
finally {
if(bf != null) {
try {
bf.close();
}
catch(IOException ignored) {}
}
}
return -1;
}

Categories

Resources