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
Related
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));
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 a freshman in Neo4J. I think I am also a freshman in Java though I have learn it for neary 2 years.
I want to save and read a picture in neo4j database, I have a InputStream instance, Its cotent is a picture data. I have a Resoucre Object. it has a byte[] property used to save the picture data. so I do that
public static Resource getResourceInstance(InputStream in, String title) throws IOException{
StringBuilder sb = new StringBuilder();
BufferedInputStream input = new BufferedInputStream(in);
int b;
while((b = input.read()) != -1){
sb.append(b);
}
input.close();
in.close();
return new Resource(sb.toString().getBytes(), title, 0, 0);
}
then I use a transaction to save it to neo4j. and I check it by neo4j-server. in database, the byte array is number like 51,52,45 and so on
the second step I want to read the byte array from database.
I put it in Resource Object. and use FileOutputStream read it the code like this
images = resource.getImage();
String titleString = resource.getTitle();
String path = "images" + File.separator + titleString + ".jpg";
System.out.println(Paths.get(path).toRealPath());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(path)));
out.write(images);
out.close();
this is a Java web project.
I don't know why I have to create a file in path(String path = "images" + File.separator + titleString + ".jpg";) at first.
though I do so, I can't open the file like a picture.
I am very dispirited now. and I don't konw how to do. can you help me?
thank you very much.
PS:
my english is poor,bet your tolerating.
don't do this in the first place.
store the picture on a filesystem or a public storage like s3, dropbox etc. and save the url or filename in the neo4j property.
If you want to read a file into a byte[] create an array of the file.length() size and read into that array using the right offset until is. read() returns -1
Seam application using tomcat and postgresql 9.0.3
App allows users to download word documents that are saved in the DB as BLOB and defined in the bean as a byte array.
These word documents have been uploaded by users in xml format.
When I use this code with Tomcat(5) in Windows, it works just fine. When used with Tomcat (v. 6.0.24) on a Linux server, I get the behavior that the contents are displayed as HEX code in the Downloaded file???
At first I thought that the server was missing some fonts, files with Fonts that are definitely on the server show the same behavior. Even TXT files do the same thing.
The code for doing the download is as follows:
byte[] wordDoc = createApptLetter();
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/msword");
fileName = letter.getFileName();
response.addHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentLength(wordDoc.length);
OutputStream os = response.getOutputStream();
//log.error(response.getContentType());
os.write(wordDoc);
os.flush();
os.close();
facesContext.renderResponse();
facesContext.responseComplete();
edit: here is createApptLetter method:
private byte[] createApptLetter() {
LetterTemplate template = appointmentHome.getInstance().getLetterTemplate();
Client client = appointmentHome.getInstance().getClientRegistration().getEligibilityCycle().getClient();
String sageClinic = appointmentHome.getInstance().getFacility().getName();
String apptDate = appointmentHome.getInstance().getAppointmentDateString();
String apptTime = appointmentHome.getInstance().getAppointmentTimeString();
String notes = appointmentHome.getInstance().getAppointmentNotes();
String longDateFormat = SageConstantsEnum.DateFormats.LONGDATEFORMAT.getDescription();
SimpleDateFormat df = new SimpleDateFormat(longDateFormat);
String today = df.format(new Date());
//StringBuilder sbTemplate = new StringBuilder(new String(template.getLetterTemplateText()));
String xmlTemplate = new String (template.getLetterTemplateText());
xmlTemplate = xmlTemplate.replace("letterDate", today);
xmlTemplate = xmlTemplate.replace("apptDate", apptDate);
xmlTemplate = xmlTemplate.replace("apptTime", apptTime);
xmlTemplate = xmlTemplate.replace("apptNotes", notes);
xmlTemplate = xmlTemplate.replace("sageClinic", sageClinic);
xmlTemplate = xmlTemplate.replace("clientName", client.getFullname());
xmlTemplate = xmlTemplate.replace("clientCity",client.getMailingAddress().getAddress().getCity());
xmlTemplate = xmlTemplate.replace("clientAddress", client.getMailingAddress().getAddress().getStreetaddress());
xmlTemplate = xmlTemplate.replace("clientState",client.getMailingAddress().getAddress().getState());
xmlTemplate = xmlTemplate.replace("clientZip", client.getMailingAddress().getAddress().getZipcode());
return xmlTemplate.getBytes();
}
Change the content type of your response to "application/octet-stream". This works for any kind of file. There is an example with JSF. In my example, I'm using a a4j:htmlCommandLink from RichFaces, since you're using Seam i guess you won't have any problem.