Cannot write to csv file using BufferedWriter - csv

I am trying to append a row at the end of my csv file using the code below
public class Register {
public static void add(int k,int m,int id1) throws Exception
{
ClassLoader classLoader = Register.class.getClassLoader();
try{
FileWriter fw = new FileWriter(new File(classLoader.getResource("data/dataset.csv").getFile()),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
I am calling this class from a servlet using a loop as I need to add 5 lines to my csv. Everything runs fine, but nothing gets added to the csv file. Please help.

You need to close the FileWriter object to flush the content into the file as shown below:
FileWriter fw = null;
BufferedWriter bw = null;
try{
fw = new FileWriter(new File(classLoader.
getResource("data/dataset.csv").getFile()),true);
bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
} finally {
if(bw != null) {
bw.close();
}
if(fw != null) {
fw.close();
}
}
As a side note, ensure that you are closing the resources (like the writer objects above) inside the finally block (which you are not doing).

Related

How to write test result in CSV file using selenium

I have to add result at the last column of each row. I have to test user successfully login with correct email and password the "PASS" is append to last else "FAIL" and go with the second row and check the result of each row.
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Selenium Drivers\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.facebook.com");
// This will load csv file
CSVReader reader = null;
try{
reader = new CSVReader(new FileReader("C:\\Users\\src\\com\\elements\\demo.csv"));
}catch (Exception e) {
e.printStackTrace();
}
String[] cell;
while ((cell=reader.readNext())!=null){
for(int i=0;i<1;i++){
String emailid=cell[i];
String password=cell[i+1];
driver.findElement(By.id("email")).sendKeys(emailid);
driver.findElement(By.id("pass")).sendKeys(password);
driver.findElement(By.id("loginbutton")).click();
String outputFile = "C:\\Users\\src\\com\\elements\\demo.csv";
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
if(driver.getTitle().equals("Log1 in to Facebook | Facebook"))
{
csvOutput.write("Pass"); //Your selenium result.
//csvOutput.endRecord();
//csvOutput.close();
}
else if (driver.getTitle().equals("Log in to Facebook | Facebook"))
{
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try this code.
String outputFile = "test.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists){
csvOutput.write("result");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Pass/Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
OR
If we want to use writeNext() method which take string array as a parameter then
String csv = "D:\\test.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Try other option.
FileWriter writer = new FileWriter("D:/test.csv",false);
writer.append(" ");
writer.append(',');
writer.append("UserName");
writer.append(',');
writer.append("Password");
writer.append(',');
writer.append("Pass/Fail");
writer.append('\n');
//generate whatever data you want
writer.flush();
writer.close();

Exception on readerNew.GetEnumerator(), ResX file Could not find a part of the path

I have an app using windows forms that goes through all the resource files in a new release writes the name value and comment to a csv file. I am ResXResourceReader and the method GetEnumerator to create a IDictionaryEnumerator and go through each resource and add the key and value to a dictionary. Im getting exceptions on some files, for example:
{[System.ArgumentException: ResX file Could not find a part of the path 'C:\ibml\SoftTrac CaptureSuite\Utilities\TranslationUtility\TranslationUtility\bin\resources\accept.png'. Line 12017, position 5. cannot be parsed. ---> System.Xml.XmlException: Could not find a part of the path 'C:\ibml\SoftTrac CaptureSuite\Utilities\TranslationUtility\TranslationUtility\bin\resources\accept.png'. Line 12017, position 5. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\ibml\SoftTrac CaptureSuite\Utilities\TranslationUtility\TranslationUtility\bin\resources\accept.png'.
My code for this is below:
private List<object> GetNewResxStrings(List<object> NewlyAddedResxFiles)
{
bool breaker = true;
Dictionary<string, int> Exceptionslist = new Dictionary<string, int>();
foreach (var resxfile in NewlyAddedResxFiles)
{
breaker = true;
while (breaker)
{
using (FileStream fsNew = File.Open(resxfile.ToString(), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
ResXResourceReader readerNew = new ResXResourceReader(fsNew);
try
{
IDictionaryEnumerator dictNew = readerNew.GetEnumerator();
while (dictNew.MoveNext())
{
NewFilesAddedToCurrentVersion.Add(dictNew.Key, dictNew.Value);
}
Dictionary<object, object> temp = new Dictionary<object, object>(NewFilesAddedToCurrentVersion);
NewUtilityResxDictionary.Add(fsNew.Name.ToString(), temp);
NameOfChangeNew.Clear();
NameOfChangeOld.Clear();
NewFilesAddedToCurrentVersion.Clear();
breaker = false;
}
catch (Exception E)
{
Exceptionslist.Add(E.ToString(), 1);
breaker = false;
break;
}
}
}
}
return NewlyAddedResxFiles;
}
I once had this error after I c/p a path from explorer. Turned out there was a hidden char in the path. Between C and : if I recall. Could that be the problem? Check in excel with MID or LEN.

Writing to .json.gz file using jackson object mapper

I need to create a .json.gz file using an ArrayList
void func(ArrayList<AirConfig> configList)
{
String filePath = "abc.json.gz";
File file = new File(filePath);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(file, configList);
}
This however dosent really work because when I try to unzip the file using the following command
gzip -cd configMasterAirport_Test.json.gz > configMasterAirport_Test.json
I get the following error,
abc.json.gz: not in gzip format
How do I rewrite my code so that the a compressed json is generated but I'm still able to use the Object Mapper
You require only a small change.
void func(ArrayList<AirConfig> configList)
{
FileOutputStream fStream = null;
GZIPOutputStream zStream = null;
try
{
String filePath = "abc.json.gz";
fStream = new FileOutputStream(filePath);
zStream = new GZIPOutputStream(new BufferedOutputStream(fStream));
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(zStream, configList);
}
finally
{
if (zStream != null)
{
zStream.flush();
zStream.close();
}
if (fStream != null)
{
fStream.flush();
fStream.close();
}
}
}

Runtime error on Integer.parseInt(); i am trying to compare the content in the file and the new value obtained from the method

/*the below code is i am trying for the notification of new mail i am trying to fetch the prestored value into the file and compare it to the new value from the method
public static void main(String args[]) throws MessagingException{
try {
Notification n= new Notification();
int a =n.Notification();
BufferedReader br = null;
//read from the earlier file value of the total messages
String sCurrentLine;
br = new BufferedReader(new FileReader("Notification.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
int b = Integer.parseInt(sCurrentLine);
if (a>b){
System.out.println("you have "+(a-b)+" new Messsages");
}else{
System.out.println("NO New message");
}
//write the new value of the total messages to the file
Writer output = null;
File file = new File("Notification.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(String.valueOf(a));
output.close();
} catch (IOException ex) {
Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
}
}
If the file you are reading from only contains a number that you require, maybe this is what you have to do:
if ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
int b = Integer.parseInt(sCurrentLine);
// do other stuff
}
else
{
// file empty
}

SSIS Scripting Component: Get child records for creating Object

Got it working - Posted My solution below but will like to know if there is better way
Hello All
I am trying to create Domain Event for a newly created (after migration) domain object in my database.
for Objects without any internal child objects it worked fine by using Script Component. The problem is in how to get the child rows to add information to event object.
Ex. Customer-> Customer Locations.
I am creating Event in Script Component- as tranformation- (have reference to my Domain event module) and then creating sending serialized information about event as a column value. The input rows currently provide data for the parent object.
Please advise.
Regards,
The Mar
Edit 1
I would like to add that current I am doing processsing in
public override void Input0_ProcessInputRow(Input0Buffer Row)
I am looking for something like create a a data reader in this function
loop through data rows -> create child objecta nd add it to parent colelction
Still on google and PreExecute and ProcessInput Seems something to look at .
This is my solution. I am a total newbie in SSIS , so this may not be the best solution.
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
IDTSConnectionManager100 connectionManager;
SqlCommand cmd = null;
SqlConnection conn = null;
SqlDataReader reader = null;
public override void AcquireConnections(object Transaction)
{
try
{
connectionManager = this.Connections.ScriptConnectionManager;
conn = connectionManager.AcquireConnection(Transaction) as SqlConnection;
// Hard to debug failure- better off logging info to file
//using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt"))
//{
// outfile.Write(conn.ToString());
// outfile.Write(conn.State.ToString());
//}
}
catch (Exception ex)
{
//using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt"))
//{
// outfile.Write(" EEEEEEEEEEEEEEEEEEEE"+ ex.ToString());
//}
}
}
public override void PreExecute()
{
base.PreExecute();
cmd = new SqlCommand("SELECT [CustomerLocation fields] FROM customerlocationView where custid=#CustId", conn);
cmd.Parameters.Add("CustId", SqlDbType.UniqueIdentifier);
}
public override void PostExecute()
{
base.PostExecute();
/*
Add your code here for postprocessing or remove if not needed
You can set read/write variables here, for example:
Variables.MyIntVar = 100
*/
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
Collection<CustomerLocation> locations = new Collection<CustomerLocation>();
cmd.Parameters["CustId"].Value = Row.id;
// Any error always saw that reader reamians open on connection
if (reader != null)
{
if (!reader.IsClosed)
{
reader.Close();
}
}
reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
// Get Child Details
var customerLocation = new CustomerLocation(....,...,...,);
customerLocation.CustId = Row.id;
locations.Add(customerLocation);
}
}
var newCustomerCreated = new NewCustomerCreated(Row.id,,...,...,locations);
var serializedEvent = JsonConvert.SerializeObject(newCustomerCreated, Formatting.Indented,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Row.SerializedEvent = serializedEvent;
Row.EventId = newCustomerCreated.EventId;
...
...
...
....
..
.
Row.Version = 1;
// using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt", true))
// {
// if (reader != null)
// {
// outfile.WriteLine(reader.HasRows);
//outfile.WriteLine(serializedEvent);
// }
// else
// {
// outfile.Write("reader is Null");
// }
//}
reader.Close();
}
public override void ReleaseConnections()
{
base.ReleaseConnections();
connectionManager.ReleaseConnection(conn);
}
}
One thing to note is that a different approach to create connection is to
get the connection string from connectionManager and use it to create OLEDB connection.