How to write test result in CSV file using selenium - csv

I have to add result at the last column of each row. I have to test user successfully login with correct email and password the "PASS" is append to last else "FAIL" and go with the second row and check the result of each row.
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Selenium Drivers\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.facebook.com");
// This will load csv file
CSVReader reader = null;
try{
reader = new CSVReader(new FileReader("C:\\Users\\src\\com\\elements\\demo.csv"));
}catch (Exception e) {
e.printStackTrace();
}
String[] cell;
while ((cell=reader.readNext())!=null){
for(int i=0;i<1;i++){
String emailid=cell[i];
String password=cell[i+1];
driver.findElement(By.id("email")).sendKeys(emailid);
driver.findElement(By.id("pass")).sendKeys(password);
driver.findElement(By.id("loginbutton")).click();
String outputFile = "C:\\Users\\src\\com\\elements\\demo.csv";
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
if(driver.getTitle().equals("Log1 in to Facebook | Facebook"))
{
csvOutput.write("Pass"); //Your selenium result.
//csvOutput.endRecord();
//csvOutput.close();
}
else if (driver.getTitle().equals("Log in to Facebook | Facebook"))
{
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Try this code.
String outputFile = "test.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists){
csvOutput.write("result");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Pass/Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
OR
If we want to use writeNext() method which take string array as a parameter then
String csv = "D:\\test.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Try other option.
FileWriter writer = new FileWriter("D:/test.csv",false);
writer.append(" ");
writer.append(',');
writer.append("UserName");
writer.append(',');
writer.append("Password");
writer.append(',');
writer.append("Pass/Fail");
writer.append('\n');
//generate whatever data you want
writer.flush();
writer.close();

Related

Java heap space issue while creating Apache poi Workbook

I am trying to convert a large xlsx sheet to csv using the example given here and here . But it is throwing the below error on line
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(file));
Error
Caught throwable Java heap space
java.lang.OutOfMemoryError: Java heap space
at java.io.ByteArrayOutputStream.<init>(ByteArrayOutputStream.java:77)
Is there any efficient way to convert large xlsx sheet to csv without increasing heap memory?
My code is as below-
try
{
// Get the workbook object for XLSX file
// XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(file));
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(file));
for(int i=0;i<wBook.getNumberOfSheets();i++)
{
XSSFSheet sheet = wBook.getSheetAt(i);
fileName = convertedFileLocation + sheet.getSheetName() + ".csv";
FileOutputStream fos = new FileOutputStream(fileName);
//System.out.println(wBook.getSheetAt(i).getSheetName());
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = cellIterator.next();
data.append("\"" + cell.getStringCellValue() + "\",\r\n");
}
}
fos.write(data.toString().getBytes());
fos.close();
}
wBook.close();
}
Edited---
I am using XSSF as suggested by #axel and #gagravarr in the comment and using the class method as below. Though it is creating the converted.csv file the csv file is empty. Any idea what I am doing wrong
private boolean convertToCSV2(File file)
{
try {
OPCPackage p = OPCPackage.open(file.getPath());
String convertedFileLocation = siteConfigService.getProperty(CONVERTEDFOLDER);
String convertedFileName = convertedFileLocation+"converted.csv";
PrintStream pout=new PrintStream(convertedFileName);
XLSX2CSV xlsToCSV = new XLSX2CSV(p, pout, -1);
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}

Xml To Json Conversion with same value needed in Json Without Exponential Form

I convert Xml Data to Json Data and my input in xml file or text file is:-
//**xml input:- <data>34123456.00</data>**
String jsonFileName = "src\\main\\resources\\Light.json";
try {
File xmlFile = new File("src\\main\\resources\\output.txt");
InputStream inputStream = new FileInputStream(xmlFile);
StringBuilder builder = new StringBuilder();
int ptr;
while ((ptr = inputStream.read()) != -1) {
builder.append((char) ptr);
}
String xml = builder.toString();
JSONObject jsonObj = XML.toJSONObject(xml);
System.out.print(jsonObj);
FileWriter fileWriter =
new FileWriter(jsonFileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
bufferedWriter.write(jsonObj.toString(PRETTY_FACTOR));
bufferedWriter.close();
} catch (IOException ex) {
System.out.println(
"Error writing to file '"
+ jsonFileName + "'");
} catch (Exception e) {
e.printStackTrace();
} /* json output is :- {"data":3.4123456E7}
I want Output as :- {"data":34123456.00} */
but i dont want exponential form in json format i want complete number so how i do this in Java ?
JSONObject jsonObj = XML.toJSONObject(xml,true);
write above line instead of
JSONObject jsonObj = XML.toJSONObject(xml);
this solves my problem.

Cannot write to csv file using BufferedWriter

I am trying to append a row at the end of my csv file using the code below
public class Register {
public static void add(int k,int m,int id1) throws Exception
{
ClassLoader classLoader = Register.class.getClassLoader();
try{
FileWriter fw = new FileWriter(new File(classLoader.getResource("data/dataset.csv").getFile()),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
I am calling this class from a servlet using a loop as I need to add 5 lines to my csv. Everything runs fine, but nothing gets added to the csv file. Please help.
You need to close the FileWriter object to flush the content into the file as shown below:
FileWriter fw = null;
BufferedWriter bw = null;
try{
fw = new FileWriter(new File(classLoader.
getResource("data/dataset.csv").getFile()),true);
bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
} finally {
if(bw != null) {
bw.close();
}
if(fw != null) {
fw.close();
}
}
As a side note, ensure that you are closing the resources (like the writer objects above) inside the finally block (which you are not doing).

Android studio: Can't find obvious file location in c:?

Every time I run this code, I get the message "File not found" in my exception however, I don't understand why is that when I literally have the file I'm looking for sitting at the root of my c:?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView testMEtext = (TextView) findViewById(R.id.testMEtext);
//
JSONParser parser = new JSONParser();
try {
//File temp = new File("C:/Windows/outdoorWeather.json");
//String path = temp.getAbsolutePath();
//testMEtext.setText(path);
**Object obj = parser.parse(new FileReader("/C:/outdoorWeather.json"));**
JSONObject jsonObject = (JSONObject) obj;
String oTemp = (String) jsonObject.get("Fahrenheit temperature");
testMEtext.setText(oTemp);
}
catch (FileNotFoundException e) {
e.printStackTrace();
testMEtext.setText("File not found");
}
catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I don't think you can interact with objects outside of your emulator. To solve it try referring to these.
Load a simple text file in android studio
How can I read a text file in android
Reading a simple text file

Runtime error on Integer.parseInt(); i am trying to compare the content in the file and the new value obtained from the method

/*the below code is i am trying for the notification of new mail i am trying to fetch the prestored value into the file and compare it to the new value from the method
public static void main(String args[]) throws MessagingException{
try {
Notification n= new Notification();
int a =n.Notification();
BufferedReader br = null;
//read from the earlier file value of the total messages
String sCurrentLine;
br = new BufferedReader(new FileReader("Notification.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
int b = Integer.parseInt(sCurrentLine);
if (a>b){
System.out.println("you have "+(a-b)+" new Messsages");
}else{
System.out.println("NO New message");
}
//write the new value of the total messages to the file
Writer output = null;
File file = new File("Notification.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(String.valueOf(a));
output.close();
} catch (IOException ex) {
Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
}
}
If the file you are reading from only contains a number that you require, maybe this is what you have to do:
if ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
int b = Integer.parseInt(sCurrentLine);
// do other stuff
}
else
{
// file empty
}