I am new to groovy. I have the following code where I want to print the Strings on the console, which doesn't work:
import java.io.FileWriter;
import java.util.Arrays;
import java.io.Writer;
import java.util.List;
//Default separator
char SEPARATOR = ',';
//get path of csv file (creates new one if its not exists)
String csvFile = "c:";
println "========================= csvFile";
println csvFile;
String[] params = {"hello"};
writeLine(params, SEPARATOR);
//function write line in csv
public void writeLine(String[] params, char separator)
{
boolean firstParam = true;
println params;
StringBuilder stringBuilder = new StringBuilder();
String param = "";
for (int i = 0; i < params.length; i++)
{
//get param
param = params[i];
println param;
//if the first param in the line, separator is not needed
if (!firstParam)
{
stringBuilder.append(separator);
}
//Add param to line
stringBuilder.append(param);
firstParam = false;
}
//prepare file to next line
stringBuilder.append("\n");
//add to file the line
println stringBuilder.toString();
}
It gives the following output:
in groovy to declare array you have to use square brackets:
String[] params = ["hello"]
btw whole code could be simplified to this:
String[] params = ["hello"]
def writeLine(params, separator=','){
println params.join(separator)
}
writeLine(params)
Related
I want to remove strings starting with # or // from the lines array.
It is not working.
Here is the code (excluding the preliminaries like reading the file etc):
def file = new File("$_file").text.replaceAll("\\r\\n|\\r|\\n", " ");
String[] lines_ = file.split("\\s*;\\s*");
println(lines_);
for(line in lines_)
{
if(line.take(1) =='#' || line.take(2) == '//')
{
remove(lines_ , line);
}
}
Here is the remove function
public static String[] remove(String[] input, String deleteMe)
{
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
Here is the $_file
canvas cvs {
width:100,
dfdf:60
}
;
//this is a comment;
#also a comment;
sprite ball{
body : hr,
Image: here
}
;
Thanks.
You can read the lines from the file with readLines(), then just call findAll like so:
String[] lines = new File("$_file")
.readLines()
.findAll { !it.startsWith('#') && !it.startsWith('//') }
I did it!
I changed remove function to:
static String[] remove(String[] str_array , String what){
List<String> list = new ArrayList<String>(Arrays.asList(str_array));
list.remove(what);
str_array = list.toArray(new String[0]);
return str_array;
}
and remove(lines_,line) to lines_ = remove(lines,line)
And its ok now!
I have below code in Groovy. Basically what I'm trying is to read the set of Input records and merge them into 1 or more records with common key combination.
The Key combination is as shown below. After reading the input file, I have written the key and fields into HashMap ( see code). But now I need to check the key in the input file , if the key is seen then I have write the output record otherwise I just need to write a output record as without merging. My questions
what is the command to insert a field in Output record ?.
import java.util.Properties;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
for( int i = 0; i < dataContext.getDataCount(); i++ ) {
InputStream is = dataContext.getStream(i);
Properties props = dataContext.getProperties(i);
reader = new BufferedReader(new InputStreamReader(is));
/* This is how to declare HashMap */
def forcastMap = [:]
String Key;
String Shipfrom = "";
String Item = "";
String Fcast = "";
String Shipto = "";
String Planned_Arrival_Date = "";
String Qty = "";
String PrevKey = "";
List<String> line = null
while ((line = reader.readLine()) != null)
{
if(line.length() > 20) //Make sure it is a data line so we can do substring manipulation
{
Shipfrom = line.substring(35,12)
Item = line.substring(50,50)
Fcast = line.substring(10,50)
Shipto = line.substring(75,10)
Planned_Arrival_Date = line.substring(85,8)
Qty = line.substring(90,12)
Key = (Shipfrom + Item + Fcast + Shipto)
forcastMap.put(Key,Planned_Arrival_Date,Qty)
if key != PrevKey {
}
}
}
//dataContext.storeStream(is, props);
}
I'm trying to get this program's groupPairs function to take the six Strings in an initial String array [One,Two,Three,Four,Five,Six] and create a new String array of half the size (3) with the original six Strings grouped sequentially in pairs [OneTwo,ThreeFour,FiveSix], and then return that resulting new String[] to the main method.
import java.util.*;
public class Application
{
static String[] groupPairs(String[] array)
{
String[] newArray = new String[(array.length)/2];
int count=0;
for(String string:newArray)
{
newArray[count]=array[count].append(array[count+1]);
count=count+2;
}
return newArray;
}
public static void main(String args[]) //main method, don't worry about this
{
String[] list = new String[5];
list[0]="One";
list[1]="Two";
list[2]="Three";
list[3]="Four";
list[4]="Five";
list[5]="Six";
String[] list2 = groupPairs(list);
}
}
When trying to compile the program, I get this error:
Application.java:11: cannot find symbol
symbol : method append(java.lang.String)
location: class java.lang.String
newArray[count]=array[count].append(array[count+1]);
^
Any ideas on how to fix this line so that my new array will have concatenated pairs of the original String[] values would be greatly appreciated!
You cannot perform append operation on array. Try the following.
String[] list = new String[6];
list[0] = "One";
list[1] = "Two";
list[2] = "Three";
list[3] = "Four";
list[4] = "Five";
list[5] = "Six";
String[] list2 = new String[list.length / 2];
for (int i = 0, j = 0; i < list.length; i++, j++)
{
list2[j] = list[i] + list[++i];
}
I see that you can't use string tokenizer on an array because you cant convert String() to String[]. After a length of time I realized that if the inputFromFile method reads it line by line, I can tokenize it line by line. I just don't know how to do it so that it returns the tokenized version of it.
I'm assuming in the line=in.ReadLine(); line I should put StringTokenizer token = new StringTokenizer(line,",").. but it doesn't seem to be working.
Any help? (I have to tokenize the commas).
public class Project1 {
private static int inputFromFile(String filename, String[] wordArray) {
TextFileInput in = new TextFileInput(filename);
int lengthFilled = 0;
String line = in.readLine();
while (lengthFilled < wordArray.length && line != null) {
wordArray[lengthFilled++] = line;
line = in.readLine();
}// while
if (line != null) {
System.out.println("File contains too many Strings.");
System.out.println("This program can process only "
+ wordArray.length + " Strings.");
System.exit(1);
} // if
in.close();
return lengthFilled;
} // method inputFromFile
public static void main(String[] args) {
String[] numArray = new String[100];
inputFromFile("input1.txt", numArray);
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == null) {
break;
}
System.out.println(numArray[i]);
}// for
for (int i=0;i<numArray.length;i++)
{
Integer.parseInt(numArray[i]);
}
}// main
}// project1
This is what I meant:
while (lengthFilled < wordArray.length && line != null) {
String[] tokens = line.split(",");
if(tokens == null || tokens.length == 0) {
//line without required token, add whole line as it is
wordArray[lengthFilled++] = line;
} else {
//add each token into wordArray
for(int i=0; i<tokens.length;i++) {
wordArray[lengthFilled++] = tokens[i];
}
}
line = in.readLine();
}// while
There can be other approaches as well. For instance, you can use a StringBuilder to read everything as one big string and them split it on your required tokens etc. The above logic is just to point you in right direction.
Could you please point out where is the bug in my code?
I have a simple text file with the following data structure:
something1
something2
something3
...
It results a String[] where every element is the last element of the file. I can't find the mistake, but it goes wrong somewhere around the line.setLength(0);
Any ideas?
public String[] readText() throws IOException {
InputStream file = getClass().getResourceAsStream("/questions.txt");
DataInputStream in = new DataInputStream(file);
StringBuffer line = new StringBuffer();
Vector lines = new Vector();
int c;
try {
while( ( c = in.read()) != -1 ) {
if ((char)c == '\n') {
if (line.length() > 0) {
// debug
//System.out.println(line.toString());
lines.addElement(line);
line.setLength(0);
}
}
else{
line.append((char)c);
}
}
if(line.length() > 0){
lines.addElement(line);
line.setLength(0);
}
String[] splitArray = new String[lines.size()];
for (int i = 0; i < splitArray.length; i++) {
splitArray[i] = lines.elementAt(i).toString();
}
return splitArray;
} catch(Exception e) {
System.out.println(e.getMessage());
return null;
} finally {
in.close();
}
}
I see one obvious error - you're storing the same StringBuffer instance multiple times in the Vector, and you clear the same StringBuffer instance with setLength(0). I'm guesing you want to do something like this
StringBuffer s = new StringBuffer();
Vector v = new Vector();
...
String bufferContents = s.toString();
v.addElement(bufferContents);
s.setLength(0);
// now it's ok to reuse s
...
If your problem is to read the contents of the file in a String[], then you could actually use apache common's FileUtil class and read in an array list and then convert to an array.
List<String> fileContentsInList = FileUtils.readLines(new File("filename"));
String[] fileContentsInArray = new String[fileContentsInList.size()];
fileContentsInArray = (String[]) fileContentsInList.toArray(fileContentsInArray);
In the code that you have specified, rather than setting length to 0, you can reinitialize the StringBuffer.