Forum Discussion

PramodYadav's avatar
PramodYadav
Contributor
7 years ago

Troubleshooting Tip: Script fails while trying to create a file on run time in a folder

Situation: Sometimes we want to create folders on run time based on say a Test scenario name picked from an excel. And then we wish to create many logfiles or test result files into this folder. In some cases you may find that the files are not created inside the folder.

 

Possible root cause: Check for a space in the name (say in excel cell). If there is a space in the end, although the folder will be created but when you are trying to create a file in this folder, it will fail. Check the below code example:

 


// Tip : Trying to create files in folder names with spaces results in error
// Make a folder
folderPath = 'c:/testfileGroovy /'    // Note the extra sapce after folder name. If you remove this, the script runs fine, else it fails.


folder = new File(folderPath)
folder.mkdir()

// make a file
sRequestFile = folderPath + "testfile.txt "
def oFile = new File(sRequestFile)

// Add content to file
xmlContent = "test content"
oFile.write(xmlContent, "UTF-8")

 

// log file location
log.info "Backup file created: " + sRequestFile

2 Replies

  • Lucian's avatar
    Lucian
    Community Hero

    Trailing spaces often mean trouble. I would suggest to implement a regex to manipulate the folderPath in the first place. For instance:

     

    // Get the folder path
    folderPath = 'c:/testfileGroovy /'
    
    // Clean the folder path
    folderPath = folderPath.replaceAll(" /", "/")

    Cheers!

    • PramodYadav's avatar
      PramodYadav
      Contributor

      Good idea ! 

       

      To make it even more foolproof (for more than one spaces), we can use: 

       

      // Make a folder
      folderPath = 'c:/testfileGroovy/'
      log.info "folderPath with spaces : $folderPath"

      // clean the fodler path
      folderPath = 'c:/testfileGroovy                       /'
      folderPath = folderPath.replaceAll(~/ / ,'')
      log.info "folderPath cleared from spaces : $folderPath"

       

      P.S: Ofcourse the condition is we don't use spaces in folder names (which is actually not a good practice if you have anything to run on command line).