I have written a simple SQL query to fetch few columns from a table.
I have created a OIM Script, which is currently running a SQL query and exporting that in a CSV. However, I am looking for to add date in the file name but not able to find any clue.
I am using CSVWritter.
CSVWriter writer = new CSVWriter(new FileWriter("Path", false));
ResultSetMetaData Mdata = rs.getMetaData();
What is the exact statement what to add in this to get the date in the file name?
Expected file name: Filename_Date.csv
Maybe get the current Date as a string when creating the filewriter and then just append it to the name as follows:
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
new FileWriter("Filename_" + date + ".csv", false);
You can also change the format of the timestamp using the formatting rules of the simple date format: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Full timestamp:
String fileName = String.format("%s.csv", DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()));
Thank you everyone for your response, finally figured out.
String filepath = "C:\\Users\\Test\\";
String filename = filepath + "Output_" + new SimpleDateFormat("d MMMM yyyy").format(new Date()) + ".csv";
CSVWriter writer = new CSVWriter(new FileWriter(filename, false));
Related
I am trying to write some data into a csv file but some of them are written at the end of the line and there is a blank space between each row. I have also tried do collect data into an ArrayList of strings and then use the method csvWriter.writeAll but it gives me the same result.
try(FileWriter fileWriter1 = new FileWriter(csvPath)){
CSVWriter csvWriter = new CSVWriter(fileWriter1);
//Impostazione di Git e della repo.
Git git = Git.open(new File(Cpath));
Repository repository = FileRepositoryBuilder.create(new File(Cpath));
String repo = String.valueOf(repository);
logger.info(repo);
List<Ref> branches = git.branchList().call();
for (Ref ref : branches)
{
logger.info(ref.getName());
}
Iterable<RevCommit> commits = git.log().all().call();
for (RevCommit revCommit : commits) { //itero tutti i commit.
String pattern = "MM/dd/yyyy HH:mm:ss";
DateFormat df = new SimpleDateFormat(pattern);
String date = df.format(revCommit.getAuthorIdent().getWhen());
String[] columns = {date, revCommit.getFullMessage()};
csvWriter.writeNext(new String[]{date, revCommit.getFullMessage()});
}
csvWriter.flush();
csvWriter.close();
}
The CSV format loosely follows the RFC 4180. But most cvs writers consistenly use a \r\n (MS/DOS convention) end of file.
When you read that with an editor (or a terminal) that expects only one single \n for an end of line (Unix convention), you wrongly see additional lines when the file is perfectly correct.
Ref: Wikipedia
I am trying to write some data to txt file using PrintStream.println. Some times it is working fine, But some times it is crashing the application. When i saw the result file, It contains <0x00> very huge amount of time. After that nothing printed in file.
Please find the below used code.
SimpleDateFormat sdf = new SimpleDateFormat("[MM/dd HH:mm:ss:SSS] ")
Date date_value = new Date();
String currentDateandTime = sdf.format(date_value);
FileOutputStream fileOutputStream = new FileOutputStream("fileName", true);
PrintStream plt_cbl_stream = new PrintStream(fileOutputStream);
plt_cbl_stream.println(currentDateandTime);
plt_cbl_stream.flush();
Can some one suggest me, What is the issue. Please find the details captured from created file.
Log captured from created file :
[20/01 15:30:24:865]
[20/01 15:30:24:8<0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00>68]
[20/01 15:30:24:872]
[20/01 15:30:24:877]
[20/01 15:30:24:892]
<0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00>
Placed the reports have overrided all the resultsi would like to print in a table with results but when i printed it overriding the results and it is printing only one line
am passing the values form other class file to print the results
i have tried using Buffered writer for writing the code
public void createTestSummaryHTMLTable(String sample,String samp[le,String sample,String passedText,String status) throws IOException {
File file=new File("C:\\AutomationResults\\Forms\\",foldername);
if(!file.exists()){
file.mkdir();}
final String FILE_PATH =(file+"/"+formname);
//final String FILE_PATH = "C:\\AutomationResults\\Forms\\"+formname;
final String FILE_EXTENSION = "html";
DateFormat df = new SimpleDateFormat("yyyyMMdd"); // add S if you need milliseconds
String filename = FILE_PATH + "_"+ df.format(new Date()) + "." + FILE_EXTENSION;
File file2 = new File(filename);
// if file doesnt exists, then create it
if (!file2.exists()) {
file2.createNewFile();
}
BufferedWriter html = new BufferedWriter(new FileWriter(file2));
html.write("<html><body bgcolor='#E6E6FA'><table border=1 cellpadding=0>");
html.write("<title>Automation Summary report </title>");
html.write("<br>");
html.write("<center><strong><em>Batch report heading</em></strong>");
html.write("<span style ='float; right;position:relative;right:30px;font weight:bold'>"+new Date().toString()+"</span>");
html.write("<tr>");
addlabel1(html,"Test Step Name");
addlabel1(html,"Test Step Description");
addlabel1(html,"Status");
addlabel1(html,"Screenshot");
html.write("</tr>");
html.write("<tr>");
html.newLine();
addlabel(html,sample);
addlabel(html,sample);
String status1 = "Passed";
if (status1.equals(status))
{
html.write("<td width='20'style='color:#00F00;font-weight:bold;text-align:center'>"+status+"</td>");
} else {
html.write("<td width='20'style='color:#A52A2A;font-weight:bold;text-align:center'>"+status+"</td>");
}
addlabel(html,"Screenshot");
html.write("</tr>");
html.write("</table></body></html>");
html.close();
}
Oh, I think i guessed your problem. The file written is a single long line.
That is because write only writes what you give it. You need to put a \n at the end of all your strings.
Alternatively, use Printwriter's println method to output to your file.
You can try adding a boolean parameter to FileWriter that helps to specify whether it should append to or override the existing content. If you pass true, it would open the file for writing in append mode.
Please change this line:
BufferedWriter html = new BufferedWriter(new FileWriter(file2));
To this:
BufferedWriter html = new BufferedWriter(new FileWriter(file2, true));
the actualresult
header is displaying for every row i dont need the header to display for all the rows result am getting is
expected result is
header should display only once
I am trying to get data out of a CSV data. However, if I try to read the data so I can use the individual data inside it, it prints extra stuff like:
x����sr��java.util.ArrayListx����a���I��sizexp������w������t��17 mei 2017t��Home - Gastt��4 - 1t��(4 - 0)t��
With this code:
FileInputStream in = openFileInput("savetest13.dat");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String[]> resultList = new ArrayList();
String csvLine;
while ((csvLine = reader.readLine()) != null){
String[] row = csvLine.split(",");
out.println("while gepakt");
out.println(row);
date = row[0];
out.println("date: "+date);
resultList.add(row);
txtTest.setText(date);
}
But whenever I read the file to check what data it contains, I get the exact same data as I put in. But I can't manage to split the data with stuff:
FileInputStream in = openFileInput("savetest13.dat");
ObjectInputStream ois = new ObjectInputStream(in);
List stuff = (List) ois.readObject();
txtTest.setText(String.valueOf(stuff));
[17 mei 2017, Home - Guest, 2 - 1, (2 - 0), ]
I am trying to get them separated into date, names, score1, score2
.
Which of the 2 would be better to use and how can I get the correct output, which I am failing to obtain?
You are not writing CSV to your output file, rather than that your are using standard java serialization ObjectOutputStream#writeObject(...) to create that file. try using a CSV library to write/read data in CSV format (see hier) and before that, start here to learn about CSV because
[17 mei 2017, Home - Guest, 2 - 1, (2 - 0), ]
is not csv, but only the output of toString of the list you are using.
Here is an easy way to write the CSV file formatted correctly. This is a simple example which does not take into account the need to escape any commas found in your data.You can open the file created in Excel, Google Sheets, OpenOffice etc. and see that it is formatted correctly.
final String COMMA = ",";
final String NEW_LINE = System.getProperty("line.separator");
ArrayList<String> myRows = new ArrayList<String>();
// add comma delimited rows to ArrayList
myRows.add("date" + COMMA +
"names" + COMMA +
"score1" + COMMA +
"score2"); // etc.
// optional - insert field names into the first row
myRows.add(0, "[Date]" + COMMA +
"[Names]" + COMMA +
"[Score1]" + COMMA +
"[Score2]");
// get a writer
final String fileName = "myFileName.csv";
final String dirPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
File myDirectory = new File(dirPath);
FileWriter writer = new FileWriter(new File(myDirectory, fileName));
// write the rows to the file
for (String myRow : myRows) {
writer.append(myRow + NEW_LINE);
}
writer.close();
I have a servlet witch is generating a .xls file and then it's sending the generated file to the user for download with the code below:
// Write the output to a file
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter=
new SimpleDateFormat("yyyy_MMM_dd");
String dateNow = formatter.format(currentDate.getTime());
String path = "webapps/myapp/exports/";
String fileName = ("Table_export_"+ dateNow + ".xls");
FileOutputStream fileOut = new FileOutputStream(path+fileName);
wb.write(fileOut);
fileOut.close();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
The file is saved on the server with a size of 5 kb, but after the browser dialog and after choosing save or open, the file is empty and the size is 0 kb. I can not understand what is wrong.
I'm fighting with this issue for about 2 hours without a success. I have tried to set the full path:
response.setHeader("Content-Disposition","attachment;filename="path+fileName);
But I got a document with a strange name and it also was 0 kb.
I'm pretty sure that I'm missing something really small, but as a junior developer I still can not figure it out.
Since you already have a method that can write your file to an output stream you can simply change your code this way to send it to the user :
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MMM_dd");
String dateNow = formatter.format(currentDate.getTime());
String fileName = ("Table_export_"+ dateNow + ".xls");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
OutputStream outputStream = response.getOutputStream();
try {
wb.write(outputStream);
} finally {
outputStream.close();
}
It won't be saved on your server HDD though.
The method HttpServletResponse#getOutputStream() allows you to access the stream of bytes that will be sent back to the client.
When you used the format -
String path = "webapps/myapp/exports/";
String fileName = ("Table_export_"+ dateNow + ".xls");
...
response.setHeader("Content-Disposition","attachment;filename="path+fileName);
Was the filename "webapps%2Fmyapps%2Fexports%2fTable_export_....xls"?
Als the filesize would have been zero because you are not putting any data in the file