GroovyScript Read from file and save in Property - groovy

I'm trying to read content from a file and then save it in a property in SoapUi.
What the file looks like (test.txt):
1231434324
1231414144
2413131231
4142131231
2131231231
My code:
File files = new File("/Temp/test.txt") // File
def lines = files.readLines(); //
lines.each {
System.out.println it
testRunner.testCase.testSteps["Properties"].setPropertyValue( "test", it )
};
For some reason it is only saving the last value (1231434324) in the property.
The below example actually saves all the values to the property but it also inserts square brackets in the beginning and at the end of the property value.
[123123123123, 123124234353, 231231231241, 213123123123]
File files = new File("/Temp/test.txt")
def lines = files.readLines();
testRunner.testCase.testSteps["Properties"].setPropertyValue( "test", "$lines" )

You can read the entire file contents into a String first, then set it all at once:
String value = new File('/Temp/test.txt').text
testRunner.testCase.testSteps['Properties'].setPropertyValue('test', value)
UPDATE
To get the total lines of the file, you could do this:
int count = value.split('\n').size()

Related

How to use contains() to check if a String is inside the ArrayList?

I need to search a String in a text file that the content in the text file will always be appended(in other method). For example String "abcdefg" need to be search exactly same in the file.
ArrayList<String> List = new ArrayList<String>();
FileReader filereader = new FileReader(file);
BufferedReader bufferreader = new BufferedReader(filereader);
String linetxt;
while((linetxt = bufferreader.readLine())!=null)
{
List.add(linetxt);
List.add("\r\n");
}
System.out.println("Please enter a string: ");
String usern = input.next();
System.out.println(List);
if ((List.contains(usern.substring(0,usern.length()))));
{
System.out.println("String existed.");
}
bufferreader.close();
The Test File current content (will always be added new content):
abcde12345
This is my code, but it occurs a problem that I will always get "String existed" no matter what I input(the String I input is not in the text file but it still printing that the String existed).
How can I modify my code to make that if my input is contained in the ArrayList, it will return "String existed"?
Is it any other ways to search a String in a text file(the content of text file will be appended in other method)?
Thanks.............. Hope everyone safe.

How can I turn a txt file into a string just using its path?

So I have a program that turns a .txt file into a string to then send it via bluetooth to a printer, the problem is that right now I'm doing it using the file name but I wanted to do it only using the path of the file, this has to do with the fact that I need to search on the folder for any existing txt files and if there are any I need to print the first one and then delete it, so I can't be doing it by using the file's name. This is my code so far:
private fun readFile() String {
val file = File(storage/emulated/0/IS4-PDF-RDP/00233116695912019091310005913BLUETOOTH.txt)
var ins InputStream = file.inputStream()
read contents of IntputStream to String
var content = ins.readBytes().toString(Charset.defaultCharset())
return content
}
You can find the first file in the folder read it and then delete it as per your requirements
File("/storage/emulated/0/IS4-PDF-RDP/").walk().find {
it.extension == "txt"
}?.apply {
inputStream().readBytes().toString(Charset.defaultCharset())
delete()
}

Rename PDF file

I would like to create a custom module that renames the generated PDF files by taking a generated filename string containg some field values from index fields, batch fields etc.
So when it comes to batch processing i could go for this (setupTransformator contains the parsed values from the custom storage strings)
public void ProcessBatch(IBatch batch)
{
IACDataElement batchElement = GetBatchElementFromBatch(batch);
IACDataElementCollection currentDocuments = GetDocumentsFromBatchElement(batchElement);
IACDataElement customStorageStrings = GetCustomStorageStringsFromBatch(batch);
IACDataElementCollection batchFields = GetElementsByName(batchElement, ResourcesKofax.BATCH_FIELDS, ResourcesKofax.BATCH_FIELD);
setupTransformator = new SetupTransformator(customStorageStrings);
for (int i = 0; i < currentDocuments.Count; i++)
{
int currentDocumentIndex = i + 1;
IACDataElement currentDocument = currentDocuments[currentDocumentIndex];
IACDataElementCollection indexFields = GetElementsByName(currentDocument, ResourcesKofax.INDEX_FIELDS, ResourcesKofax.INDEX_FIELD);
string targetFilename = setupTransformator.GetFilename(batchElement, currentDocument, batchFields, indexFields);
string documentFilePath = currentDocument[ResourcesKofax.PDF_GENERATION_FILE_NAME];
// rename the PDF file
}
batch.BatchClose(KfxDbState.KfxDbBatchReady, KfxDbQueue.KfxDbQueueNext, 0, string.Empty);
}
private IACDataElement GetBatchElementFromBatch(IBatch batch)
{
IACDataElement rootElement = batch.ExtractRuntimeACDataElement(0);
return rootElement.FindChildElementByName(ResourcesKofax.BATCH);
}
private IACDataElementCollection GetDocumentsFromBatchElement(IACDataElement batchElement)
{
return GetElementsByName(batchElement, ResourcesKofax.DOCUMENTS, ResourcesKofax.DOCUMENT);
}
private IACDataElement GetCustomStorageStringsFromBatch(IBatch batch)
{
IACDataElement setupElement = batch.ExtractSetupACDataElement(0);
IACDataElementCollection batchClasses = GetElementsByName(setupElement, ResourcesKofax.BATCH_CLASSES, ResourcesKofax.BATCH_CLASS);
IACDataElement batchClass = batchClasses[1];
return batchClass.FindChildElementByName(ResourcesKofax.BATCH_CLASS_CUSTOM_STORAGE_STRINGS);
}
private IACDataElementCollection GetElementsByName(IACDataElement dataElement, string rootName, string targetName)
{
return dataElement.FindChildElementByName(rootName).FindChildElementsByName(targetName);
}
Do I have to use the File.Move method or is there a method from the Kofax library I can use?
File names should be handled by Export Connectors only. As long as the batch is in the system you shouldn't have their names changed as this could lead to data loss and corruption.
This especially applies when using field values for a PDF's name - since values are subject to change as long as the batch is in the system, how would you accommodate this? Nothing is stopping your users from processing a batch in your custom module and set the batch back to validation and change one or more fields.
Speaking of the Export Connector and its API:
By default, Kofax offers two methods to export a PDF - both on the ReleaseData object (this is taken from the API docs):
CopyKofaxPDFFile: Copy the PDF file that belongs to a document into the export PDF path that is defined during export setup.
CopyKofaxPDFFileToPath: Copy the PDF file that belongs to a document into a specified path (the path is a string input argument for this method).
Both methods make use of something that you could define during Setup - for example, CopyKofaxPDFFile makes use of the KofaxPDFPath property. I am not sure if there's a property reserved for the file name.
I usually stick with the KofaxPDFProperty exposed during runtime and perform a File.Copy operation. I wouldn't recommend moving the file or deleting it as this is something that KC automatically handles once the batch was exported successfully (in theory, there could be another export, or the export might just fail).
Use the ReleaseData object to access field values, and string interpolation to define the PDF's final name.

Remove all previous text before writing

I am writing a text file and each time i write i want to clear the text file.
try
{
string fileName = "Profile//" + comboboxSelectProfile.SelectedItem.ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), true))
{
sw.WriteLine(fileName);
MessageBox.Show("Default is set!");
}
DefaultFileName = "Default//DefaultProfile.txt";
}
catch
{
}
How do I do this? I want to remove all previous content from DefaultProfile.txt.
I actually have to know the method or way (just a name could be) to remove all content from the text file.
You could just write an empty string to the existing file:
File.WriteAllText(#"Default\DefaultProfile.txt", string.Empty);
Or change the second parameter in the StreamWriter constructor to false to replace the file contents instead of appending to the file.
You can look at the Truncate method
FileInfo fi = new FileInfo(#"Default\DefaultProfile.txt");
using(TextWriter txtWriter = new StreamWriter(fi.Open(FileMode.Truncate)))
{
txtWriter.Write("Write your line or content here");
}
The most straightforward and efficient technique is to use the StreamWriter constructor's boolean parameter. When it's set to false it overwrites the file with the current operation. For instance, I had to save output of a mathematical operation to a text file. Each time I wanted ONLY the current answer in the text file. So, on the first StreamWriter operation, I set the boolean value to false and the subsequent calls had the bool val set to true. The result is that for each new operation, the previous answer is overwritten and only the new answer is displayed.
int div = num1 / denominator;
int mod = num1 % denominator;
Console.Write(div);
using (StreamWriter writer = new StreamWriter(FILE_NAME, false ))
{
writer.Write(div);
}
Console.Write(".");
using (StreamWriter writer = new StreamWriter(FILE_NAME, true))
{
writer.Write(".");
}
You can use FileMode.Truncate. Code will look like
FileStream fs = new
FileStream(filePath, FileMode.Truncate, FileAccess.Write )
{
fs.Close();
}
System.IO.File.Delete, or one of the System.IO.FileStream constructor overloads specifying FileMode.Create
Simply change the second parameter from true to false in the contructor of StreamWriter.
using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), **false**))
See StreamWriter Contructor

Replace part of a filename in C#

I have a folder with .pdf files. In the names of most files I want to replace specific string with another string.
Here's what I've written.
private void btnGetFiles_Click(object sender, EventArgs e)
{
string dir = tbGetFIles.Text;
List<string> FileNames = new List<string>();
DirectoryInfo DirInfo = new DirectoryInfo(dir);
foreach (FileInfo File in DirInfo.GetFiles())
{
FileNames.Add(File.Name);
}
lbFileNames.DataSource = FileNames;
}
Here I extract all file names in List Box.
private void btnReplace_Click(object sender, EventArgs e)
{
string strReplace = tbReplace.Text; // The existing string
string strWith = tbWith.Text; // The new string
string dir = tbGetFIles.Text;
DirectoryInfo DirInfo = new DirectoryInfo(dir);
FileInfo[] names = DirInfo.GetFiles();
foreach (FileInfo f in names)
{
if(f.Name.Contains(strReplace))
{
f.Name.Replace(strReplace, strWith);
}
}
And here I want to do the replacing, but something is going wrong. What?
It sounds like you want to change the name of the file on disk. If so then you need to use the File.Move API vs. changing the actual string which is the file name.
One other mistake you are making is the Replace call itself. A string in .Net is immutable and hence all of the mutating APIs like Replace return a new string vs. changing the old one in place. To see the change you need to assign the new value back to a variable
string newName = f.Name.Replace(strReplace, strWith);
File.Move(f.Name, newName);
f.Name is a read-only property. f.Name.Replace(..) simply returns a new string with the filename you want, but never actually changes the file.
I suggest something along the following, though I haven't tested it:
File.Move(f.Name, f.Name.Replace(strReplace, strWith));
Replace return another string, it doesn't change the original string.
So you need to write
string newName = f.Name.Replace(strReplace, strWith);
of course this doesn't change the name of the file on disk.
If that was your intention then you should look at
File.Move(f.Name, newName);
also keep in mind that File.Move will fail with an exception if the destination file exists.
See here for an example
At a first glance, seems like you're not reassigning the replaced string to your f.Name variable. Try this:
string NewFileName = f.Name.Replace(strReplace, strWith);
File.Copy(f.Name, NewFileName);
File.Delete(f.Name);
When you call string.Replace this doesn't alter your existing string. Instead it is returning a new string.
You need to change your code to something like this:
if(f.Name.Contains(strReplace))
{
string newFileName = f.Name.Replace(strReplace, strWith);
//and work here with your new string
}

Resources