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

custom-keyword

#1
  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: https://www.homeandlearn.co.uk/java/write_to_textfile.html