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


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


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


just prints to the screen in console mode.


Always remember to close the filewriter afterwards using


Otherwise you could end up with a half written file.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »