tags:

views:

239

answers:

3

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!!

+5  A: 

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");
    }
}
cynicalman
thanks! Is it possible to specify the location of the tempfile?
JLau
Just change the line: File f = File.createTempFile("selenium", "txt");to: File f = new File("path to file")";
Redbeard
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.
Janusz
+1  A: 

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.

Bill the Lizard
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 Martínez
@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. :)
Bill the Lizard
Thanks for the link!
JLau
A: 

Always remember to close the filewriter afterwards using

writer.close()

Otherwise you could end up with a half written file.