I would like to rename lastModified() json as filename+"processing" in jenkins with groovy. I am unsuccessfully doing :
JSON_BASE_PATH="/json_repo/"
def file = new File(JSON_BASE_PATH).listFiles()?.sort { it.lastModified() }?.find{it=~/.json$/}
file.renameTo( new File( file.getName() + ".processing") )
print "Filename is : " + file
How to rename it ?
You actually already have the answer in your code, you're just not storing it in a variable! new File( file.getName() + ".processing")
An instance of File isn't the actual entry on the file system, it's just a representation of one. So after you perform the rename, you need to work with the File instance that represents the renamed file system entry:
JSON_BASE_PATH="/json_repo/"
def file = new File(JSON_BASE_PATH).listFiles()?.sort { it.lastModified() }?.find{it=~/.json$/}
def modifiedFile = new File("${file.getName()}.processing")
/* Check their existence */
println "${file.getName()} exists? ${file.exists()}"
println "${modifiedFile.getName()} exists? ${modifiedFile.exists()}"
/* Rename the file system entry using the File objects */
file.renameTo(modifiedFile)
/* See what we have */
println "Original filename is: ${file}"
println "${file.getName()} exists? ${file.exists()}"
println "Modified Filename is: ${modifiedFile}"
println "${modifiedFile.getName()} exists? ${modifiedFile.exists()}"
Update : renameTo is working fine. However file var is not reflecting the rename name. How to get new rename name ?
Related
This is going to be a really stupid question - how do I open a file in the Filing Cabinet and read it in, line by line, using SuiteScript? Every example I can find online seems to start in the middle, taking for granted knowledge that I don't possess.
Is there a simple example somewhere online I've not found? All I need is for it to:
Open file (giving file name and folder)
Read the first line
Read the second line
....
Close the file.
In Suitescript 2.0 use the N/file module. The module can only be used in server side (not client) scripts. Reference Suite Answer Id: 43524 for N/file module and Suite Answer Id: 43520 for Script Types.
require(['N/file', 'N/record'], function(file, record) {
//use file name and folder and 'N/search' module to find the file id if necessary
// load file
var myFile = file.load({
id: '__' //enter the file internal id, absolute or relative file path
})
//get the # of lines
var arrLines = myFile.getContents().split(/\n|\n\r/);
// loop through each line, skipping the header
for (var i = 1; i < arrLines.length - 1; i++) {
//split the 1 line of data into an array. If the file was a csv file, each array position holds a value from the columns of the 1 line of data
var content = arrLines[i].split(',');
// get values from the columns of a CSV file
var column1 = content[0]; //first column
var column2 = content[1]; //second column
//can use the column data above to i.e. create new record and set default value, update existing records, write the data elsewhere
//to check each line for a given value
arrLines[i].includes('keyword'); //returns true or false
}
});
You can get the suitescript api documentation here
https://docs.oracle.com/cloud/latest/netsuitecs_gs/docs.htm
look at the file module
Let's keep it simple:
For SuiteScript 1.0:
var arrLines = nlapiLoadFile({fileinternalid}).getValue().split(/\n|\n\r/);
For SuiteScipt 2.0:
var arrLines = file.load({
id: {fileinternalid}
});
arrLines.getValue().split(/\n|\n\r/);
arrLines.description = 'My CSV File'
var fileId = arrLines.save();
...
// Add additional code
I try to delete files which i can find in folderPath. But I want delete only that, which have in name "Jenkins".
How to define in list to delete only that file.?
Example :
In C:\test\test have 3 files, want delete that which have Jenkins in name :
import groovy.io.FileType
String folderPath = "C:\\test" + "\\" + "test"
def list = []
def dir = new File("$folderPath")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
list.each {
println it.findAll() == "Jenkins" // Just files witch include in list "Jenkins" name
}
Thanks for tips !
Here you go:
Use either of the below two:
import groovy.io.FileType
String folderPath = "C:/test/test"
new File(folderPath).eachFile (FileType.FILES) { file ->
//Delete file if file name contains Jenkins
if (file.name.contains('Jenkins')) file.delete()
}
or
Below one uses FileNameFinder class
String folderPath = "C:/test/test"
def files = new FileNameFinder().getFileNames(folderPath, '**/*Jenkins*')
println files
files.each { new File(it).delete()}
I'm trying to rename files in a directory using Groovy but I can't seem to understand how it works.
Here is my script:
import groovy.io.FileType
def dir = new File("C:/Users/דודו/Downloads/Busta_Rhymes-Genesis-(Retail)-2001-HHI")
def replace = {
if (it == '_') {
' '
}
}
String empty = ""
dir.eachFile (FileType.FILES) { file ->
String newName = file.name
newName = newName.replaceAll(~/Busta_Rhymes/, "$empty")
newName = newName.replaceAll(~/feat/, "ft")
newName = newName.replaceAll(~/-HHI/, "$empty")
newName = newName.replaceAll(~/--/, "-")
newName = newName.collectReplacements(replace)
file.renameTo newName
println file.name
}
When I run this, the names of the files aren't changed as expected. I'm wondering how could I get this to work.
There are a number of things wrong here:
Your dir variable is not the directory; it is the file inside the directory that you actually want to change. Change this line:
dir.eachFile (FileType.FILES) { file ->
to this:
dir.parentFile.eachFile (FileType.FILES) { file ->
The renameTo method does not rename the local name (I know, very counterintuitive), it renames the path. So change the following:
String newName = file.name
to this:
String newName = file.path
Now, for some reason beyond my comprehension, println file.name still prints out the old name. However, if you look at the actual directory afterwords, you will see that the file is correctly renamed in the directory.
I move a file to a folder. Is there any way to not overwrite a file with that name?
For example, folder contains a file named: file1.pdf. How can I move another file named: file1.pdf into that folder so that the name get changed to e.g. file1-1.pdf, file1-2.pdf to prevent the original file from getting overwritten.
I'm using substring to do that but it's quite long and awful code.
You could use something like this:
def save = { File dir, String name ->
int version = 1
def splitName = name.split(/\./, 0).with { it -> it.length == 1 ? [it[0], ''] : [it[0..-2].join('.'), ".${it[-1]}"] }
def rename = { String prefix, String ext -> "$prefix-$version$ext" }
while (new File(dir, name).exists()) {
name = rename(*splitName)
version++
}
println "Save the file as $name"
}
save(new File('/tmp'), 'file.txt')
Which assuming you have a file /tmp/file.txt and a file /tmp/file-1.txt already, prints out: Save the file as file-2.txt
I'm using groovy script in soapUI. I want to save my response to file. I'm using the following script. The file is created, but it's content is empty.
//get dir target from property
def dirTarget = context.expand( '${#Project#SnapShotDirTarget}' )
def fileDir = new File(dirTarget);
if(!fileDir .exists()) {
fileDir .mkdirs()
}
def currentDate = new Date().format("yyyy-MM-dd hh:mm")
def fileName = "Snapshot - "+currentDate+".txt"
def resultsFile= new File(fileDir , context.expand( fileName) )
if(!resultsFile.exists()) {
resultsFile.createNewFile();
}
resultsFile.append("Post URL:"+messageExchange.getEndpoint()+'\n' );
resultsFile.append("Request:"+'\n' );
resultsFile.append(messageExchange.getRequestContent()+'\n' );
resultsFile.append("Response:"+'\n' );
resultsFile.append(messageExchange.getResponseContent()+'\n' );
If you are running Windows the colon between the hour and minutes in the filename is going to cause some problems, since colon is not allowed in Windows file names.
When I tried running the script it created an empty file called "Snapshot - 2014-08-14 09" (everything after and including the colon is missing)
Changing the colon to something else makes the trick.
def currentDate = new Date().format("yyyy-MM-dd hh_mm")
The call to createNewFile is not necessary by the way. The append call will create the file if it doesn't exist.