How to create a Katalon method (Keyword) for writing to a text file with Java

  1. Start Katalon Studio
  2. Click File > New > Keyword
  3. Browse for the target Package or create a new one for example, tools
  4. Input a new “Class Name” for example, WriteFile
  5. Click OK
  6. Input the following code into the method (the @Keyword annotation is not required)
//Use "CTRL+SHIFT+O" to add imports
package tools
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

public class WriteFile {

private String path;
private boolean append_to_file = false;

//Writeover file
public WriteFile (String file_path) {
path = file_path; }

//Appends to file
public WriteFile (String file_path, boolean append_value){
path = file_path;
append_to_file = append_value;
}

public void WriteToFile (String textline) throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textline);
print_line.close(); } 
}

  1. To append to the file, add the following to the body of the test case
//Use "CTRL+SHIFT+O" to add imports
import tools.WriteFile as WriteFile

String file_name = "C:\\Folder_Name\\OutPut.txt"
WriteFile data = new WriteFile(file_name, true)
data.WriteToFile("This-is-a-line-of-text")
println("One record written to file...")

  1. To overwrite the file, add the following to the body of the test case
//Use "CTRL+SHIFT+O" to add imports
import tools.WriteFile as WriteFile

String file_name = "C:\\Folder_Name\\OutPut.txt"
WriteFile data = new WriteFile(file_name)
data.WriteToFile("This-is-a-line-of-text")
println("One record written to file...")

The full Tutorial can be found here: java for complete beginners - writing to text files

5 Likes

This helped me get going on writing to External data sources today. Just want to state something that should have been incredibly obvious, but this section should go within the Test Case itself, not within the Custom Keyword.

Thanks for plotting this out so I can setup a data extract for later review.