Selenium - writing values to a .txt file - java

I am attempting to pull some values from a webpage, with the intention of writing them into a .txt file for manual validation. I have looked around the web and cannot find the way to achieve this in my scenario. I will be writing the code in java if possible.
I have the following html code available for the element:
<td class="value" data-bind="text:
$data.value">Windows Server 2012 R2 Standard 64-bit</td>
And the xpath for the element is:
html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]
Is anyone able to help me create a sample piece of code that will;
a) Pick up the value and write it into a text file. Preferably with a prefix of 'Operating system'.
b) Save the file with a unique ID, My thought is to suffix the filename with a datetime stamp.
c) I will have multiple elements to read from the webpage and then write to the text file, around 8 or so, is there any consideration I need to be aware of for writing multiple values to a .txt file and format them neatly?
Hopefully I have included everything I need to here, if not just ask!
Many thanks in advance. KG

Thats not as difficult as it seems. I use similar function for me to write a log into a txt file.
At first I would write all Information in one String variable. It's helpful to format the Information before writing it into the variable. If you collect all Informations your could write this String very simple to a txt file using the following Code:
private static void printToTxt(){
String info = "Collected Informations";
String idForTxtFile = new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(new Date());
File file = new File("Filename" + idForTxtFile);
try {
FileWriter fw = new FileWriter(file, true);
//if you want to write the linesperator ("\n) as they are in the txt you should use the following Code:
String lineSeparator = System.getProperty("line.separator");
String[] ouput = info.split("\n");
for (int i = 0; i <= output.length-1; i++) {
fw.write(output[i]);
fw.write(lineSeparator);
}
//instead you could only use:
fw.write(info);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getLocalizedMessage);
}
Little bit late, but here is my version, maybe you could use some additional to yours!

I have reviewed the answers on the question How do I create a file and write to it in Java?, thanks for the nudge #Mardoz, and with some playing around I have it doing what I needed. Here is the final code, with the date also being tagged into the filename:
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-yyyy HH-mm") ;
// Wait for the element to be available
new WebDriverWait(Login.driver,10).until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]")));
Writer writer = null;
// Find the value and write it to the text file 'Smoke_004 DD-MM-yyyy HH-mm.txt'
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Smoke_004 " + dateFormat.format(date) + ".txt"), "utf-8"));
writer.write("Operating System : " + Login.driver.findElement
(By.xpath("html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]"))
.getText());
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
Thanks for your input #Mardoz and #ErstwhileIII

Related

Binary file I/O with custom object - Java

I am trying to write data to a binary file and am having difficulty. When I run this method I don't get any output to the file. Also when it comes to writing my "Date" object, I can't seem to find a write method that takes it as a parameter. The object consists of an int month, day, and year. How can I write it into a binary file properly?
Also, does "File" work for binary as well? I have only previously used it for regular .txt files and I'm not sure if it can be used the same way in this situation. Thanks!
Here is my write method:
private void writeBinary(){
//String fileName = getUserInput();
String fileTest = "BinaryMonster.bin";
File file = new File(fileTest);
DataOutputStream out;
try{
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, true)));
if(!(file.exists())){
file.createNewFile();
System.out.println("New file created...");
}
for(int i = 0; i < monsterAttacks.size(); i++){
out.writeInt(monsterAttacks.get(i).getID());
out.write(monsterAttacks.get(i).getDate()); //getting error
out.writeUTF(monsterAttacks.get(i).getName() + monsterAttacks.get(i).getLocation() + monsterAttacks.get(i).getReporter());
}
} catch(IOException e) {
e.printStackTrace();
}
}
It is giving error because you are writing whole object of date into the file using DataOutputStream, which don't allow you to do that.
Write it in the form of String into the file. It will be better.
out.writeUTF(monsterAttacks.get(i).getDate().toString());
But if you want to save the whole object into the file, then you need to use ObjectOutputStream which write whole serialized objects into the file.
And it is better approach to flush and close the file.
out.flush();
out.close();

Java FileWriter not actually changing file at all

I have been looking for the past hour or so trying to find the reason for this, but have found nothing. It is a very small text file (only 4 characters at most), thus the reason I did not bother with a BufferedReader or BufferedWriter. The problem lies in the fact that while I have the writer put the variable into the file and even close the file, it does not actually keep the change in the file. I have tested this by checking the file immediately after running the method containing this code.
try {
int subtract = Integer.parseInt(secMessage[2]);
try {
String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
int comb = Integer.parseInt(deaths) - subtract;
write.write(comb);
write.close();
sendMessage(channel, "Death count updated to " + comb);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NumberFormatException e) {
e.printStackTrace();
sendMessage(channel, "Please use numbers to modify death count");
}
EDIT: Since it was asked, here is my readFile message:
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
I have already tested it and it returns the contents without error.
EDIT2: Posting the readFile method made me think of something to try, so I removed the call to it (code above also updated) and tried it again. It now writes to the file, but does not write what I want. New question will be made for this.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
You're trying to write a file named after the contents of deaths.txt. It's possible that you intend to be writing to the file itself.
From http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
Currently you are using the contents of the file instead of the file name.

Renaming a CSV file from data.csv to timestamp_data.csv using filewriter

Hello Java experts here is my question.
I currently have a code that runs some queries and outputs the data into a csv file. It currently outputs it into my desktop and saves the files.
as you can see
//csv printer
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\JChoi\\Desktop\\new Date().getTime() + data.csv")));
} catch (Exception e) {
System.out.println("I could not open the output csv file, see stacktrace below:");
e.printStackTrace();
}
although it printed the file, the file just came out to say "new Date().getTime()data.csv"
i guess im missing a step in setting the date and time. ultimately i want to get it so that when i run this file, i will get a new csv file with today's date and current time on the file. Thanks
EDIT: SOLVED
Date dNow = new Date( );
SimpleDateFormat timeStamp =
new SimpleDateFormat ("yyyy-MM-dd");
//csv printer
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\JChoi\\Desktop\\google api csv outputs\\" + timeStamp.format(dNow) +"_data.csv")));
}
thanks all
Basically
new FileWriter("C:\\Users\\JChoi\\Desktop\\new Date().getTime() + data.csv")));
Is creating a String literal (literally, making the text between the quotes what you type)
What you need to do is some variable/String concatenation, for example...
new FileWriter("C:\\Users\\JChoi\\Desktop\\" + new Date().getTime() + "data.csv")));
You should note, Date#getTime will return the number of milliseconds since the Unix epoch as a long. As such, you might want to consider using some kind of DateFormat to format the value into a more human readable format
The statement
new FileWriter("C:\\Users\\JChoi\\Desktop\\new Date().getTime() + data.csv")
Cretes file with name "C:\Users\JChoi\Desktop\new Date().getTime() + data.csv"
If you want to put actual date to file name, you should concat Strings like
new FileWriter("C:\\Users\\JChoi\\Desktop\\"+new Date().getTime() + +"data.csv")

Java -- Need help to enhance the code

I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.

How to erase existing text in a file

I'm working on an assignment for school, and am trying something beyond for extra credit. The program is to demonstrate the efficiency differences between a linear & binary search for a given array size of integers. I have a loop set up that creates an int[size] array, searches for a random number, then creates a new array of int[size*2].
The results are then written to a text file. The output writes fine, but after compiling & running the program several times, the output file has that many sections of data.
This is my code that is nested inside a try/catch block:
File output= new File("c:\\BigOhResults.txt");
int counter=2;
if (output.canWrite() && output.exists()) {
BufferedWriter out= new BufferedWriter(new FileWriter(output, true));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
}
Is there any way I can erase the text within that output file upon each time the program is run?
the reason I'm doing this is the professor requires the result printout with the data graphed. I have already completed the graphing requirement, and it works fine. I just want to have the file printout match the graph printout.
The second argument to the FileWriter constructor, which you're passing in "true", is "append". I.e. because you've set it to true, it will append your new output to the end of the file. If you pass in false instead, it will wipe the data that's there already and write it new.
Read the documentation for FileWriter. You do not want to append.
As already mentioned, the [FileWriter][1] constructor allows you to specify to clear the existing text and start at the beginning of the file. Some other remarks about the code:
The check on output.exists() is redundant after a call to output.canWrite() and isn't needed. output.canWrite() will check if the file exists and that you can write to it.
Don't forget to close the BufferedWriter object.
Like so:
if (output.canWrite()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output, false));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
} catch (IOException e) {
// Do what you want here, print a message or something
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
// Again, do what you want here
}
}
}
}
[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
Okay so I tried something and it worked. This is when you have a file that is intended to append any new text, but you want to reset/erase the contents of the file at the beginning of program execution. Hope I made sense.
PrintWriter pw1 = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt")));
pw1.close(); // Make sure the first PrintWriter object name is different from the second one.
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt", true))); // PrintWriter in append-mode. When you recreate the text file with the same name, the file contents are erased because the previous object was not in append mode.
pw.close();

Categories

Resources