Find the matching string and replace the next line - groovy

I am new to the Groovy.
If the line contains the string then replace the next line in the file.
Found something in google, but I don't want to write a new file.
newPomFile.withWriter { output ->
jars.eachLine{ line ->
if (!skipFlag)output.write(line)
skipFlag = false;
output.write("\n")
if (line.contains(calArtiName.toString().trim())){
output.write(" <version>"+calArtiVer+"</version>")
skipFlag = true;
}
}
}

You may looking for this :
File a = new File ("fileName.txt");
boolean flag = false;
a.text = a.readLines().collect{ l ->
if(flag){
flag=false;
l += " hw r u" //<=== Your code
}
flag = (l.contains('hi')) // <== Your condtion
l
}.join("\n")

Related

charAt not working for strings from a file

Im using the charAt function to find the first and second letters in a string that was read from a file but after getting the first character from the charAt(0) line, charAt(1), throws an exection that the string is too short when I know it is not. Here is the code.
while(inputFile.hasNext()){
//read file first line
String line = inputFile.nextLine();
//if the first 2 letters of the line the scanner is reading are the same
//as the search letters print the line and add one to the linesPrinted count
String lineOne = String.valueOf(line.charAt(0));
String lineTwo = String.valueOf(line.charAt(1));
String searchOne = String.valueOf(search.charAt(0));
String searchTwo = String.valueOf(search.charAt(1));
if (lineOne.compareToIgnoreCase(searchOne) == 0 && lineTwo.compareToIgnoreCase(searchTwo) == 0){
System.out.println(line);
linesPrinted++;
}
}
I've tried checking the make sure the string isn't being changed after the charAt(0) use by printing and I know it isn't and I've run the program with no probems after just removing the line so I am sure it is this that's causing the problem
The only functional change needed would to change hasNext to hasNextLine.
As one might encounter a line shorter than 2, say an empty line at the end of file, check the length.
while (inputFile.hasNextLine()) {
// read file next line
String line = inputFile.nextLine();
if (line.length() < 2) {
continue;
}
// if the first 2 letters of the line the scanner is reading are the same
// as the search letters print the line and add one to the linesPrinted count
String lineOne = line.substring(0, 1);
String lineTwo = lin.substring(1, 2);
String searchOne = search.substring(0, 1);
String searchTwo = search.substring(1, 2);
if (lineOne.equalsIgnoreCase(searchOne) && lineTwo.equalsIgnoreCase(searchTwo)) {
System.out.println(line);
linesPrinted++;
}
}
There is a problem with special chars and other languages, scripts. A Unicode code point (symbol, character) can be more than one java char.
while (inputFile.hasNextLine()) {
// read file next line
String line = inputFile.nextLine();
if (line.length() < 2) {
continue;
}
// if the first 2 letters of the line the scanner is reading are the same
// as the search letters print the line and add one to the linesPrinted count
int]} lineStart = line.codePoints().limit(2).toArray();
int]} searchStart = search.codePoints().limit(2).toArray();
String lineKey = new String(lineStart, 0, lineStart.length);
String searchKey = new String(searchStart, 0, searchStart.length);
if (lineKey.equalsIgnoreCase(searchKey)) {
System.out.println(line);
linesPrinted++;
}
}

apex parse csv that contains double quote in every single records

public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {
List<List<String>> allFields = new List<List<String>>();
// replace instances where a double quote begins a field containing a comma
// in this case you get a double quote followed by a doubled double quote
// do this for beginning and end of a field
contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
// now replace all remaining double quotes - we do this so that we can reconstruct
// fields with commas inside assuming they begin and end with a double quote
contents = contents.replaceAll('""','DBLQT');
// we are not attempting to handle fields with a newline inside of them
// so, split on newline to get the spreadsheet rows
List<String> lines = new List<String>();
try {
lines = contents.split('\n');
} catch (System.ListException e) {
System.debug('Limits exceeded?' + e.getMessage());
}
Integer num = 0;
for(String line : lines) {
// check for blank CSV lines (only commas)
if (line.replaceAll(',','').trim().length() == 0) break;
List<String> fields = line.split(',');
List<String> cleanFields = new List<String>();
String compositeField;
Boolean makeCompositeField = false;
for(String field : fields) {
if (field.startsWith('"') && field.endsWith('"')) {
cleanFields.add(field.replaceAll('DBLQT','"'));
} else if (field.startsWith('"')) {
makeCompositeField = true;
compositeField = field;
} else if (field.endsWith('"')) {
compositeField += ',' + field;
cleanFields.add(compositeField.replaceAll('DBLQT','"'));
makeCompositeField = false;
} else if (makeCompositeField) {
compositeField += ',' + field;
} else {
cleanFields.add(field.replaceAll('DBLQT','"'));
}
}
allFields.add(cleanFields);
}
if(skipHeaders)allFields.remove(0);
return allFields;
}
I use this part to parse CSV file, but i find out i cant parse when the CSV are all bounded by double quotes.
For example, i have records like these
"a","b","c","d,e,f","g"
After parsing, i would like to get these
a b c d,e,f g
From what I'm seen, the first thing you do is to split the line you get from the CSV file by commas, using this line:
List < String > fields = line.split(',');
When you do this to your own example ("a","b","c","d,e,f","g"), what you get as your list of string is:
fields = ("a" | "b" | "c" | "d | e | f" | "g"), where the bar is used to separate the list elements
The issue here is that, if you first split by commas, it will be a little more difficult to differentiate those commas that are part of a field (because they actually appeared inside quotes), from those that separate fields in you CSV.
I suggest trying do split the line by quotes, which would give you something like this:
fields = (a | , | b | , | c | , | d, e, f | , | g)
and filter out any elements of you list that are only commas and/or spaces, finally achieving this:
fields = (a | b | c | d, e, f | g)
(edited)
Is that Java you're using?
Anyways, here is a Java code that does what you're trying to do:
import java.lang.*;
import java.util.*;
public class HelloWorld
{
public static ArrayList<ArrayList<String>> parseCSV(String contents,Boolean skipHeaders) {
ArrayList<ArrayList<String>> allFields = new ArrayList<ArrayList<String>>();
// separating the file in lines
List<String> lines = new ArrayList<String>();
lines = Arrays.asList(contents.split("\n"));
// ignoring header, if needed
if(skipHeaders) lines.remove(0);
// for each line
for(String line : lines) {
List<String> fields = Arrays.asList(line.split("\""));
ArrayList<String> cleanFields = new ArrayList<String>();
Boolean isComma = false;
for(String field : fields) {
// ignore elements that don't have useful data
// (every other element after splitting by quotes)
isComma = !isComma;
if (isComma) continue;
cleanFields.add(field);
}
allFields.add(cleanFields);
}
return allFields;
}
public static void main(String[] args)
{
// example of input file:
// Line 1: "a","b","c","d,e,f","g"
// Line 2: "a1","b1","c1","d1,e1,f1","g1"
ArrayList<ArrayList<String>> strings = HelloWorld.parseCSV("\"a\",\"b\",\"c\",\"d,e,f\",\"g\"\n\"a1\",\"b1\",\"c1\",\"d1,e1,f1\",\"g1\"",false);
System.out.println("Result:");
for (ArrayList<String> list : strings) {
System.out.println(" New List:");
for (String str : list) {
System.out.println(" - " + str);
}
}
}
}

how do i make code check inputs before accepting all kinds of strings

I am trying to get a valid word from a set of scrabbled letters but all inputs (invalid ones,numbers included) are accepted by my code and checked against a list of words directly. How can i check the inputs against the displayed scrabbled letters so that only words containing letters from the scrabbled ones are accepted before checking the record?
import comp102x.IO; //a library from an edx course(COMP 102x)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.Random;
public class FormWords {
public void searchWord() throws IOException
{
Random random = new Random();
String [] randAlphs = {"o","b","e","k","a","i","c","d","f","g","h","k","u"};
int r = random.nextInt(randAlphs.length);
int a = random.nextInt(randAlphs.length);
int n = random.nextInt(randAlphs.length);
int d = random.nextInt(randAlphs.length);
int o = random.nextInt(randAlphs.length);
int m = random.nextInt(randAlphs.length);
int w = random.nextInt(randAlphs.length);
int i = random.nextInt(randAlphs.length);
int s = random.nextInt(randAlphs.length);
//prompt's user for input
String answer = JOptionPane.showInputDialog("form words with the following: " + randAlphs[r]+ randAlphs[a]+ randAlphs[n]+ randAlphs[d]+ randAlphs[o]+ randAlphs[m]+ randAlphs[w]+ randAlphs[s]);
/*searches the record to check if input exists
*/
boolean exist = searchFromRecord("record.txt", answer);
if (exist)
{
JOptionPane.showMessageDialog(null, "Congratulation!The word \"" + answer + "\" is a valid English word.");
}
else
{
// System.out.println("Sorry b ut the word \"" + answer + "\" is not a valid English word.");
JOptionPane.showMessageDialog(null, "Sorry but the word \"" + answer + "\" is not a valid English word.");
}
}
/**
* Searches the record and returns if a specified word is in the record.
*
* #param recordName The name of the record text file.
* #param word The word to be searched.
* #return true if the word presents in the record, false otherwise.
*/
private boolean searchFromRecord(String recordName, String word) throws IOException
{
// Please write your code after this line
File inputFile = new File("record.txt");
Scanner input = new Scanner(inputFile);
while(input.hasNextLine()){
if(word.equalsIgnoreCase(input.nextLine())){
return true;
}
}
return false;
}
}
Before your "prompt's user for input" code. You can use and HashSet in java and add all the letter into de HashSet. Code snippet like this:
Set<String> scrabbledLettersSet = new HashSet<String>();
scrabbledLettersSet.add(randAlphs[a]);
scrabbledLettersSet.add(randAlphs[n]);
scrabbledLettersSet.add(randAlphs[d]);
scrabbledLettersSet.add(randAlphs[o]);
scrabbledLettersSet.add(randAlphs[m]);
scrabbledLettersSet.add(randAlphs[w]);
scrabbledLettersSet.add(randAlphs[i]);
scrabbledLettersSet.add(randAlphs[s]);
Then before you do searchFromRecord method, you can use the set to check whether you input is valid or not. Code snippet is like this:
bool containsScrabbledLetters = false;
for(int i = 0 ; i < answer.length() ; ++ i) {
if (scrabbledLettersSet.contains(answer.substring(i, i + 1))) {
containsScrabbledLetters = true;
break;
}
}
boolean exist = false;
if (containsScrabbledLetters)
exist = searchFromRecord("record.txt", answer);
The above code means that if at least one letter in input string is the scrabbled letter, the input is OK, If you means all letters int the input string must exist in the scrabbled letters, you can use the following code:
bool containsScrabbledLetters = true;
for(int i = 0 ; i < answer.length() ; ++ i) {
if (!scrabbledLettersSet.contains(answer.substring(i, i + 1))) {
containsScrabbledLetters = false;
break;
}
}
boolean exist = false;
if (containsScrabbledLetters)
exist = searchFromRecord("record.txt", answer);

Read specific string from each line of text file using BufferedReader in java

my text file :
3.456 5.234 Saturday 4.15am
2.341 6.4556 Saturday 6.08am
At first line, I want to read 3.456 and 5.234 only.
At second line, I want to read 2.341 and 6.4556 only.
Same goes to following line if any.
Here's my code so far :
InputStream instream = openFileInput("myfilename.txt");
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line=null;
while (( line = buffreader.readLine()) != null) {
}
}
Thanks for showing some effort. Try this
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
double x = Double.parseDouble(parts[0]);
double y = Double.parseDouble(parts[1]);
}
I typed this from memory, so there might be syntax errors.
int linenumber = 1;
while((line = buffreader.readLine()) != null){
String [] parts = line.split(Pattern.quote(" "));
System.out.println("Line "+linenumber+"-> First Double: "+parts[0]+" Second Double:"
+parts[1]);
linenumber++;
}
The code of Bilbert is almost right. You should use a Pattern and call quote() for the split. This removes all whitespace from the array. Your problem would be, that you have a whitespace after every split in your array if you do it without pattern. Also i added a Linenumber to my output, so you can see which line contains what. It should work fine

How to recursively check for a file's existence and rename if it exist, using groovy?

How do recursively check and rename the file if it already exist by appending some incrementing number?
I wrote the below function but it gives me an exception
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'E:\Projects\repo1\in_conv1.xml' with class 'java.lang.String' to class 'java.io.File'
Code
//newFilePath = E:\Projects\repo1\old\testcustprops.xml
String newFilePath = checkForExistenceAndRename(newFilePath,false)
private String checkForExistenceAndRename(String newFilePath, boolean flag){
File f = new File(newFilePath)
if(!flag){
if(f.exists()){
//renaming file
newFilePath=newFilePath[0..-5]+"_conv${rename_count++}.xml"
f = checkForExistenceAndRename(newFilePath,false)
}
else
f = checkForExistenceAndRename(newFilePath,true)
}
else
return newFilePath
}
You are trying to do:
f = checkForExistenceAndRename(newFilePath,false)
Where f is a File. But your function returns a String
Not sure if it works or not (I haven't tested your function), but you could try:
private String checkForExistenceAndRename(String newFilePath, boolean flag){
File f = new File(newFilePath)
if(!flag){
if(f.exists()){
//renaming file
newFilePath = newFilePath[0..-5]+"_conv${rename_count++}.xml"
newFilePath = checkForExistenceAndRename(newFilePath,false)
}
else
newFilePath = checkForExistenceAndRename(newFilePath,true)
}
return newFilePath
}
Also, there's no need to use recursion...
Why not just do:
private String getUniqueName( String filename ) {
new File( filename ).with { f ->
int count = 1
while( f.exists() ) {
f = new File( "${filename[ 0..-5 ]}_conv${count++}.xml" )
}
f.absolutePath
}
}

Resources