JLau
JLau

Reputation: 323

Java noob question - how to store a string to a new text file

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

Upvotes: 2

Views: 717

Answers (3)

Marco Reimann
Marco Reimann

Reputation:

Always remember to close the filewriter afterwards using

writer.close()

Otherwise you could end up with a half written file.

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 405785

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.

Upvotes: 1

cynicalman
cynicalman

Reputation: 5881

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");
    }
}

Upvotes: 5

Related Questions