I am trying to read a file within a controller and store some data in an object, but I cant manage to save it properly. Can anyone help? I am new in Groovy/Grails...
File generals = new File("C:/Grails/Grails-3.3.0/ggts/Test/data.txt")
def line = generals.readLines()
def date = new SetDate(params)
date.save()
date.title = ${line[0]}
date.location = ${line[1]}
date.description = ${line[2]}
date.name = ${line[3]}
date.email = ${line[4]}
date.save()
You may change ${line[0]} to "${line[0]}" and all things alike if you want to use string interpolation.
And as line is a list of String, change ${line[0]} to line[0] is also ok.
Related
I am trying to automate download csv file and read data from there.
I tried with:
CSVReader reader = new CSVReader(new FileReader("D:\\File\\1453.csv"));
String [] csvCell;
//while loop will be executed till the last line In CSV.
while ((csvCell = reader.readNext()) != null) {
String FName = csvCell[0];
String LName = csvCell[1];
String Email = csvCell[2];
String Mob = csvCell[3];
String company = csvCell[4];
but the problem is here I need to give the file name while mentioning the path, here I can't write the name as it is getting changed at runtime after downloading. Please suggest
If the filename is same as the download link (even if it is partial), you can get the link from the download button or whatever element it is using getAttribute("href") and then you can use it to form the filename to read from.
String fileName = driver.findElement("<download_locator>").getAttribute("href")
CSVReader reader = new CSVReader(new FileReader("D:\\File\\" + fileName));
String [] csvCell;
//while loop will be executed till the last line In CSV.
while ((csvCell = reader.readNext()) != null) {
String FName = csvCell[0];
String LName = csvCell[1];
String Email = csvCell[2];
String Mob = csvCell[3];
String company = csvCell[4];
Have you tried this? And passing in the parameter from a method?
CSVReader reader = new CSVReader(new FileReader("D:\\File\\" + provideFileName));
I have the code below that splits a text file from IsolatedStorage, populates an Array with the data, sorts it, and then assigns it as the source for a ListPicker:
var splitFile = fileData.Split(';');
string[] testArray = splitFile;
Array.Sort<string>(testArray);
testLocationPicker.ItemsSource = testArray;
However, it doesn't seem to populating the array correctly and the sorting doesn't appear to be working as expected either.
The testArray[0] is blank, when it should be populated. When the output is shown the entry that should be at [0] appears at the bottom.
BEFORE SORTING:
AFTER SORTING:
It's only in sorting the array that it seems to screw up the order.
UPDATE: I tried the suggested:
var splitFile = fileData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[] testArray = splitFile;
Array.Sort<string>(testArray);
testLocationPicker.ItemsSource = testArray;
This still results in the second screenshot, above.
When the app first ever runs I do this:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
store.CreateDirectory("testLocations"); // Create a directory
IsolatedStorageFileStream rootFile = store.CreateFile("locations.txt"); // Create a file in the root.
rootFile.Close(); // Close File
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
string filePath = "locations.txt";
if (store.FileExists(filePath)) {
Debug.WriteLine("Files Exists");
StreamWriter sw =
new StreamWriter(store.OpenFile(filePath,
FileMode.Open, FileAccess.Write));
Debug.WriteLine("Writing...");
sw.WriteLine("Chicago, IL;");
sw.WriteLine("Chicago, IL (Q);");
sw.WriteLine("Dulles, VA;");
sw.WriteLine("Dulles, VA (Q);");
sw.WriteLine("London, UK;");
sw.WriteLine("London, UK (Q);");
sw.WriteLine("San Jose, CA;");
sw.WriteLine("San Jose, CA (Q);");
sw.Close();
Debug.WriteLine("Writing complete");
}
Then when I add to the file I do this:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
byte[] data = Encoding.UTF8.GetBytes(locationName + ";");
string filePath = "locations.txt";
if (store.FileExists(filePath))
{
using (var stream = new IsolatedStorageFileStream(filePath, FileMode.Append, store))
{
Debug.WriteLine("Writing...");
stream.Write(data, 0, data.Length); // Semi Colon required for location separation in text file
stream.Close();
Debug.WriteLine(locationName + "; added");
Debug.WriteLine("Writing complete");
}
}
I'm splitting using a ";" could this be an issue?
There's no problem with the sort: 'space' is considered to come before 'a', so it appears on top of the list. The real problem is: why do you have an empty entry to begin with?
My guess is that, when creating the file, you're separating every entry with ;, including the last one. Therefore, when parsing the data with the string.Split method, you're left with an empty entry at the end of your array.
An easy way to prevent that is to use an overload of the string.Split method that filters empty entries:
var splitFile = fileData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
I went a different way using IsolatedStorageSetting and storing Arrays/Lists to do what I wanted.
While trying to make a simple register/signup client only application for a personal project. I'm trying to load a list of users from a file, and compare them to a possible username. If the username already exists, the program will give them an error.
Here is a condensed clone of the code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.readline()
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
The user list is stored in a file so that it can opened, appended, and saved again, without being stored in the program. My current issue is that the userlist is saved as a string rather than an array. Is there a better way to do this? Thank you.
EDIT: Thanks to user lorenzo for a solution. My Friends are telling me to post a quick (really simple) copy of a for you guys who can't figure it out.
New code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.read() #Readline() changed to Read()
userlist = userlist.split('--') #This line is added
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
Example text file contents:
smith123--user1234--stacky
This line will seperate the string at the ('--') seperators and append each split part into an array:
userlist = userlist.split('--')
#Is used so that this (in the text file)
Smith123--user1234--stacky
#Becomes (in the program)
userlist = ['Smith123','user1234','stacky']
Sorry for the long post... Found it very interesting. Thanks again to Lorenzo :D.
userlist = t.readline()
reads one line from the file as a string. Iterating, then, gets characters in the string rather than words.
You should be able to get a list of strings (words) from a string with the split() method of strings or the more general re.split() function.
Well, i have this code that is supposed to check if the html is changed by first checking and downloading the html into a string, then checking again every two seconds and printing html if it has changed. The problem is that the script says it has changed all the time, and keeps giving me the same html code back.
#!/usr/bin/env python
import time
start = time.time()
from urllib.request import urlopen
data = str
html = str
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
html = data
def secondcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
if not html == data:
print(data)
while True:
secondcheck()
time.sleep(2)
print ("it took", time.time() - start, "seconds.")
Thanks in advance;)
You need to tell the interpreter to set the global html variable in the firstcheck() function.
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
global html
html = data
Right now the secondcheck() function is checking against the html value "str".
It doesn't look like you are calling firstcheck at all, so html is always going to be str. You could make it work by replacing the block inside the while True with:
while True:
firstcheck()
secondcheck()
but it would be cleaner to have a script that looked something like this
while True:
hogniergay = urlopen(url)
result = hogniergay.read()
hogniergay.close()
if result != current:
print (result)
current = result
time.sleep(2)
I keep getting a NullReferenceException at this line UserRoot.Element("User_ID").Value = User.User_ID.ToString();
What exactly am I doing wrong?
Here's the majority of the code for that method
if (File.Exists(Path2UserDB + User.User_ID.ToString() + ".db") == false)
{
File.Create(Path2UserDB + User.User_ID.ToString() + ".db");
}
XElement UserRoot = new XElement("User");
UserRoot.Element("User_ID").Value = User.User_ID.ToString();
UserRoot.Element("Full_Name").Value = User.Full_Name;
UserRoot.Element("Gender").Value = User.Gender;
UserRoot.Element("BirthDate").Value = User.BirthDate.ToString();
UserRoot.Element("PersonType").Value = User.PersonType.ToString();
UserRoot.Element("Username").Value = User.Username;
UserRoot.Element("Password").Value = User.Password;
UserRoot.Element("Email_adddress").Value = User.Email_Address;
XDocument UserDoc = new XDocument();
UserDoc.Save(Path2UserDB + User.User_ID.ToString() + ".db");
Thanks
I know that saving Usernames and Passwords in plain text is incredibly unsafe, but this is only going to be accessed by one process that I will eventually implement strong security
The Element("User_ID") method returns an existing element named <User_ID>, if any.
Since your XML element is empty, it returns null.
You should create your XML like this:
var userDoc = new XDocument(
new XElement("User",
new XElement("User_ID", User.User_ID),
new XElement("Full_Name", User.Full_Name),
new XElement("Gender", User.Gender),
...
)
);
Alternatively, you can call the Add method to add a node to an existing element.
You are getting this error, because there is no XML element called User_ID under UserRoot to set its value. If you comment it out, you will get the same error on the next line and so on for every other Element, since you haven't added Elements with thos names. To create the tree that you want, try this:
XElement UserRoot =
new XElement("User",
new XElement("User_ID", User.User_ID.ToString()),
new XElement("Full_Name", User.Full_Name),
new XElement("Gender", User.Gender),
new XElement("BirthDate", User.BirthDate.ToString()),
new XElement("PersonType", User.PersonType.ToString()),
new XElement("Username", User.Username),
new XElement("Password", User.Password),
new XElement("Email_adddress", User.Email_Address)
);
The following MSDN link on XML Tree Creation with XElement will be of help.
You want to check if the value is null or empty before running methods on it.
if(!String.IsnullorEmpty(User.User_ID))
UserRoot.Element("User_ID").Value = User.User_ID.ToString();