2

Here is my scenario:

Selenium grabbed some text on the html page and convert it to a string (String store_txt = selenium.getText("text");) - the text is dynamically generated.

Now I want to store this string into a new text file locally every time I run this test, should I use FileWriter? Or is it as simple as writing a System.out.println("string");?

Do I have to write this as a class or can I write a method instead?

Thanks in advance!!

3 Answers 3

5

Use createTempFile to create a new file every time, use FileWriter to write to the file.

import java.io.File;
import java.io.IOException;
import java.io.FileWriter;

public class Main {
    public static void main(String[] args) throws IOException {
        File f = File.createTempFile("selenium", "txt");
        FileWriter writer = new FileWriter(f);
        writer.append("text");
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! Is it possible to specify the location of the tempfile?
Just change the line: File f = File.createTempFile("selenium", "txt"); to: File f = new File("path to file")";
If you want to append the data to a File create the Filewriter with new FileWriter(File, true). The function append only appends the data to the writer not the file.
1

Yes, you need to use a FileWriter to save the text to file.

System.out.println("string");

just prints to the screen in console mode.

2 Comments

Watch out for the Path class... It's a Java 7 feature, it's included in the tutorials but no official release is available yet!
@Beau: Thanks for catching that for me. I changed my answer to link to an example that actually works. I don't know how Sun got the new tutorials to the top of the search rankings before the official release. :)
0

Always remember to close the filewriter afterwards using

writer.close()

Otherwise you could end up with a half written file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.