Results 1 to 20 of 26
Thread: creating a file
- 12-15-2009, 03:17 PM #1
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
creating a file
Hi,
Am using eclipse to develop a java application. I have created a dynamic web project in eclipse and in a JSP creating a file using FileOutputStream. The file is created in the Local Directory but I want to create a file in the project workspace itself using FileOutputStream.
Below is the sample code..
Blob test=rst.getBlob("img");
InputStream is=test.getBinaryStream();
int size=is.available();
OutputStream ot=new FileOutputStream("c:/xyz1.jpg");
byte b[]= new byte[size];
is.read(b);
ot.write(b);
This code works...it gets an image blob from database and copies the image in C directory as xyz1.jpg.
Blob test=rst.getBlob("img");
InputStream is=test.getBinaryStream();
int size=is.available();
OutputStream ot=new FileOutputStream("xyz1.jpg");
byte b[]= new byte[size];
is.read(b);
ot.write(b);
But the above code does not copy the image into the project workspace and does not throw any error either.
Thanks,
Aruna
- 12-15-2009, 03:34 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Where's it saving it to then?
Also, how are you running this? What's the web server?
- 12-15-2009, 03:45 PM #3
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
It is not saving in the project but not raising any error..I am running it on tomcat webserver. So is the case with a text file also...The code creates a Text file in the in the C directory but not in workspace.
The below is simple java class..
file11.txt is created in the C directory and prints the file content. But when I Try to create a file in the workspace usingJava Code:try { BufferedWriter out = new BufferedWriter(new FileWriter("c:/file11.txt")); out.write("tryrtyrggggggggggggguaString"); out.close(); } catch (IOException e) { } try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("c:/file11.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println ("now "+strLine); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); }
It does not throw any error and prints the content of the file, but i cannot the file in the workspace...Java Code:BufferedWriter out = new BufferedWriter(new FileWriter("file11.txt"));Last edited by Fubarable; 12-15-2009 at 03:57 PM. Reason: code tags added
- 12-15-2009, 03:47 PM #4
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
BufferedWriter out = new BufferedWriter(new
FileWriter("file11.txt"));
It does not throw any error and prints the content of the file, but i cannot find the file in the workspace...
-
Code tags added to post #3 in order to help make the code more readable. To learn how to use these, please see my signature.
- 12-15-2009, 04:33 PM #6
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
It's running on Tomcat.
Which means its root is in the relevant application folder under webapps, not the project.
So your file will be there, at a guess.
- 12-15-2009, 05:08 PM #7
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
Yes, its saving the image in C:\Documents and Settings\Aruna. My workspace is in C:\Documents and Settings\Aruna\workspace. So its saving outside the workspace.
But my tomcat is in C:\platform\apache-tomcat-6.0.20. I have no idea why this happened.
But my simple java class through which I created a text file and copied the contents. It created the text file in C:\Documents and Settings\Aruna\workspace\project1\.
For the image file, I wrote a JSP, which is in project1 WebContent folder. The JSP connects to mysql server, gets the blob image and saves the image in C:\Documents and Settings\Aruna.
For the text file, I wrote Java class, which is in project1 Src folder. The class creates a text file, appends text and prints out the content. This text file is saved in C:\Documents and Settings\Aruna\workspace\project1\.
You were right in saying the image file is stored some other place as with JSP, I was running it on webserver and the plain java class for text file, i was running it as just Java Application.
But basically I need a jsp code which gets blob image from mysql database and copies that image in the project itself so that I could be able to display the image using the img tag.
- 12-15-2009, 05:15 PM #8
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Are you running Tomcat through Eclipse?
What happens when you run your webapp in Tomcat proper, rather than via Eclipse?
I would test path things like this in the proper place, in this case in Tomcat.
If done in Tomcat I would expect it to end up in the webapps/<your-webapp> directory.
In fact, don't bother saving the image. Why not simply have the src for the img tag point to a servlet whose sole purpose is to stream the image straight from the db (with appropriate content type set, of course). So, instead of your output stream being a file output stream, use the output stream of the response.
- 12-15-2009, 05:59 PM #9
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
I have tried using response.getOutputStream() earlier. But as i was not able to solve the problem in that way switched to this procedure.
the code is:
Java Code:<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ page import="java.sql.*"%> <%@ page import="java.io.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <table> <tr> <td><h1>[COLOR="SeaGreen"][B]Books[/B][/COLOR]</h1></td> </tr> <tr> <td> <% String DRIVER = "com.mysql.jdbc.Driver"; Class.forName(DRIVER).newInstance(); Connection con=null; ResultSet rst=null; Statement stmt=null; try { String urldb="jdbc:mysql://localhost:3306/database?user=root&password=test"; con=DriverManager.getConnection(urldb); stmt=con.createStatement(); String bookid; Blob img; Blob thumb_img; //String img; //String thumb_img; String url; String category; String[] gen; InputStream sImage; byte[] imgData = null ; int count=0; int x=1; int y=1; int j=1; rst=stmt.executeQuery("select * from books where category='Social' order by publish_date desc"); x=1; y=1; while(rst.next()){ img=rst.getBlob("img"); thumb_img=rst.getBlob("thumb_img"); url=rst.getString("url"); imgData = img.getBytes(1,(int)img.length()); response.setContentType("image/jpeg"); OutputStream o = response.getOutputStream(); o.write(imgData); o.flush(); o.close(); } rst.close(); stmt.close(); con.close(); } catch(Exception e) { System.out.println(e.getMessage()); } %> </td> </tr> </table> </body> </html>
The image is displayed on the page, but the heading Books is not displayed and also I get this error on the console
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(R esponse.java:610)
at org.apache.catalina.connector.ResponseFacade.getWr iter(ResponseFacade.java:198)
at org.apache.jasper.runtime.JspWriterImpl.initOut(Js pWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffe r(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release( PageContextImpl.java:188)
at org.apache.jasper.runtime.JspFactoryImpl.internalR eleasePageContext(JspFactoryImpl.java:118)
at org.apache.jasper.runtime.JspFactoryImpl.releasePa geContext(JspFactoryImpl.java:77)
at org.apache.jsp.pages.newbooks_jsp._jspService(newb ooks_jsp.java:144)
at org.apache.jasper.runtime.HttpJspBase.service(Http JspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet .java:717)
at org.apache.jasper.servlet.JspServletWrapper.servic e(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFil e(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspSe rvlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet .java:717)
at org.apache.catalina.core.ApplicationFilterChain.in ternalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.do Filter(ApplicationFilterChain.java:206)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrep areAndExecuteFilter.doFilter(StrutsPrepareAndExecu teFilter.java:88)
at org.apache.catalina.core.ApplicationFilterChain.in ternalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.do Filter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invo ke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invo ke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke( StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invok e(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11Conn ectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run( JIoEndpoint.java:454)
at java.lang.Thread.run(Thread.java:595)
Finally I need to use the image in the html img tag. My requirement is to display an image and I have a CSS which on mouseover pops out the enlarged image along with book title and author.
and it looks like this
Java Code:<a class="thumbnail" href="<%out.println(url); %>"><img src="<%out.println(thumb_img); %>" style="margin-right:20px;" /><span><img src="<%out.println(img); %>" /><br />Title: <%out.println(rst.getString("title"));%> <br/>Authors: <%out.println(rst.getString("author"));%></span></a>Last edited by aruna.hcu; 12-15-2009 at 06:02 PM.
- 12-15-2009, 08:59 PM #10
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
Thanks for the help. I figured out that when I add
at the end in the JSP file the error is rectified. But the problem now is the image is displayed without any error but any other content is not displayed, just a single image is displayed. Do u have any idea over this?Java Code:out.clear(); out = pageContext.pushBody();
- 12-16-2009, 10:58 AM #11
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Um...I did say use a Servlet.
Basic Java web structure. Do not do anything other than display work in a JSP. It should not have any "business" logic in it (ie db interaction, or, frankly, code of any sort outside of tag libs).
The problem you have is that by the time the JSP is accessed the output to the user has begun, so streaming an image won't work...or, the image is all you'll get.
Your image tag will have something like src="servlet?id=123&any-other-parameters", where the id (and other parameters if need be) is used to access the correct image in the db. So, all the servlet does is stream that using the response output stream.
- 01-05-2010, 02:05 AM #12
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
Thanks for the help. I am developing the project using struts 2 and tiles, so instead of servlet i wrote the code in an action class to retrieve an image as below..
<img src="<s:url action="myAction"/>" style="margin-right:20px;" />
Part of my struts.xml is as below:
<package name="default" extends="struts-default">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
<result-type name="myBytesResult" class="com.icensa.action.MyBytesResult" ></result-type>
</result-types>
<action name="myAction" class="com.icensa.action.MyAction">
<result name="myImageResult" type="myBytesResult" />
</action>
My MyBytesResult class is:
public class MyBytesResult implements Result {
private static final long serialVersionUID = 1L;
public void execute(ActionInvocation invocation) throws Exception {
MyAction action = (MyAction) invocation.getAction();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("image/jpeg");
//response.setContentLength(action.getMyContentLengt h());
response.getOutputStream().write(action.getMyImage InBytes());
response.getOutputStream().flush();
}
}
And MyAction class is:
public class MyAction extends ActionSupport {
private static final long serialVersionUID = 1L;
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
byte[] imgData = null;
OutputStream o = null;
HttpServletResponse response = ServletActionContext.getResponse();
public String doDefault() {
System.out.println("doDefault()");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","pass");
stmt = con.createStatement();
rs = stmt.executeQuery("select * from books_tb where category='General' order by publish_date desc");
while (rs.next()) {
image = rs.getBlob(11);
imgData = image.getBytes(1,(int)image.length());
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
return "myImageResult";
}
public byte[] getMyImageInBytes() {
System.out.println("getMyImageInBytes()");
try{
}
catch (Exception e) {
System.out.println(e.getMessage());
}
return imgData;
}
// public String getMyContentType() { }
// public String getMyContentDisposition() {}
// public int getMyContentLength() { }
// public int getMyBufferSize() { }
}
when i run the code the image is not displayed and I get an error saying
No result defined for action com.action.MyAction and result success
In struts.xml is I provide reslut name="success" and the jsp, it does not throw an error but not displaying the image. However in any case it is not going to MyAction.java. What could i do to rectify this? I would provide the complete code is necessary..
Thanks,
Aruna
- 01-05-2010, 10:54 AM #13
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Could you put that in code tags, because the lack of formatting makes it really difficult to tell what's going on.
But first off, how do you know which image to return?
- 01-05-2010, 02:59 PM #14
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
I need to display images one by one depending on category and sorted by date as in the sql query.
let me put the code on more readable form. In the jsp am calling the image to display by:
struts.xml is as below:Java Code:<img src="<s:url action="myAction"/>" style="margin-right:20px;" />
My MyBytesResult class is:Java Code:<struts> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> <constant name="struts.devMode" value="false"/> <include file="struts-default.xml"/> <package name="default" extends="struts-default"> <result-types> <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" /> <result-type name="myBytesResult" class="com.icensa.action.MyBytesResult" ></result-type> </result-types> <action name="*Link" method="{1}" class="com.icensa.action.LinkAction"> <result name="home" type="tiles">home</result> <result name="books" type="tiles">books</result> <result name="ManageBook" type="tiles">ManageBook</result> <result name="EditBook" type="tiles">EditBook</result> </action> <action name="AddBook" class="com.icensa.action.AddBook"> <result name="input" type="tiles">ManageBook</result> <result type="tiles">books</result> </action> <action name="EditBook" class="com.icensa.action.EditBook"> <result name="error" type="tiles">ManageBook</result> <result type="tiles">EditBook</result> </action> <action name="UpdateBook" class="com.icensa.action.UpdateBook"> <result name="input" type="tiles" >EditBook</result> <result type="tiles">books</result> </action> <action name="myAction" class="com.icensa.action.MyAction"> <result name="myImageResult" type="myBytesResult" /> </action> </package> </struts>
Thanks for the help. I am developing the project using struts 2 and tiles, so instead of servlet i wrote the code in an action class to retrieve an image as below..Java Code:public class MyBytesResult implements Result { private static final long serialVersionUID = 1L; public void execute(ActionInvocation invocation) throws Exception { MyAction action = (MyAction) invocation.getAction(); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("image/jpeg"); //response.setContentLength(action.getMyContentLengt h()); response.getOutputStream().write(action.getMyImage InBytes()); response.getOutputStream().flush(); } }
<img src="<s:url action="myAction"/>" style="margin-right:20px;" />
Part of my struts.xml is as below:
<package name="default" extends="struts-default">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
<result-type name="myBytesResult" class="com.icensa.action.MyBytesResult" ></result-type>
</result-types>
<action name="myAction" class="com.icensa.action.MyAction">
<result name="myImageResult" type="myBytesResult" />
</action>
My MyBytesResult class is:
public class MyBytesResult implements Result {
private static final long serialVersionUID = 1L;
public void execute(ActionInvocation invocation) throws Exception {
MyAction action = (MyAction) invocation.getAction();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("image/jpeg");
//response.setContentLength(action.getMyContentLengt h());
response.getOutputStream().write(action.getMyImage InBytes());
response.getOutputStream().flush();
}
}
And MyAction class is:
when i run the code the image is not displayed and I get an error sayingJava Code:public class MyAction extends ActionSupport { private static final long serialVersionUID = 1L; Blob image = null; Connection con = null; Statement stmt = null; ResultSet rs = null; byte[] imgData = null; OutputStream o = null; HttpServletResponse response = ServletActionContext.getResponse(); public String doDefault() { System.out.println("doDefault()"); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","pass"); stmt = con.createStatement(); rs = stmt.executeQuery("select * from books_tb where category='General' order by publish_date desc"); while (rs.next()) { image = rs.getBlob(11); imgData = image.getBytes(1,(int)image.length()); } } catch (Exception e) { System.out.println(e.getMessage()); } return "myImageResult"; } public byte[] getMyImageInBytes() { System.out.println("getMyImageInBytes()"); try{ } catch (Exception e) { System.out.println(e.getMessage()); } return imgData; } // public String getMyContentType() { } // public String getMyContentDisposition() {} // public int getMyContentLength() { } // public int getMyBufferSize() { } }
No result defined for action com.action.MyAction and result success
In struts.xml if I provide result name="success" and the jsp, it does not throw an error but not displaying the image. However in any case it is not going to MyAction.java. What could i do to rectify this? I would provide the complete code is necessary..
Thanks,
Aruna
- 01-05-2010, 03:18 PM #15
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Well, I can never get the Struts configuration right without actually running it myself, so I'm not going to be any use there.
However, your image tag is all wrong then. That is for a single image. The action it references seems to be trying to return all images? Hard to tell since your code is still unformatted.
Also, why don't you stream it straight from the action? Or am I thinking Spring here?
- 01-05-2010, 03:31 PM #16
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
I am not sure how to stream it straight from the action. I have not done any Spring earlier so I started with struts. Can I mail you the whole code so that you could run once.
- 01-05-2010, 03:49 PM #17
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
I don't do that, I'm afraid...besides, I haven't a struts set up here since my current contract is a spring one.
Have you managed to get a normal action working?
- 01-05-2010, 04:04 PM #18
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
yes i have normal action working. In Tiles I have defined a header, body and footer. When the application runs by default it goes to the homepage. In the header I have a Menu, in which there is a Books page(that is also defined in the struts.xml, as you can see above). When i click on Books page it goes to the page but does not display the book image, which I retrieved from the Mysql. I have designed the Books page so that all books are displayed category wise and sorted by date. Initially I used to copy the book images in the project and provided the path, so it was easy.
In the books.jsp, i pass the sql query and using
I displayed the images one by one. Now the same thing but instead of storing the images in the application, I made it possible for the user to upload images to the mysql and retrieving the images. I am stuck at displaying the images. I was able to do this using servlet, but as am using struts i wrote action class. And also because am using tiles the problem became complicated for me. In struts.xmlJava Code:while(rst.next()){ <a class="thumbnail" href="<%out.println(url); %>"><img src="<%out.println("images/books/connected_small.jpg"); %>" style="margin-right:20px;" /><span><img src="<%out.println("images/books/connected.jpg"); %>" /><br />Title: <%out.println(rst.getString("title"));%> <br/>Authors: <%out.println(rst.getString("author"));%></span></a> }
Here for all other pages I provided type="tiles".Java Code:<action name="myAction" class="com.icensa.action.MyAction"> <result name="myImageResult" type="myBytesResult" /> </action>
Even then i can figure out there is problem as it has to display stream of images and am asking it to return after reading an image. But at this point i do not have any other idea.
- 01-05-2010, 04:23 PM #19
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
At this point, just to get moving, I'd be tempted to have a one-off ImageServlet, and bypass Struts if you can.
Then again, with Tiles do all your Actions have to be Tile based? Can't you just have a normal Struts Action mapped to something? An ImageAction?
- 01-05-2010, 04:30 PM #20
Member
- Join Date
- Dec 2009
- Posts
- 24
- Rep Power
- 0
Similar Threads
-
Creating JAR file goes wrong.
By dudejonne in forum New To JavaReplies: 6Last Post: 11-02-2009, 04:32 PM -
Creating a .jar file
By Wataru in forum New To JavaReplies: 3Last Post: 07-22-2009, 06:02 AM -
Creating jar file
By Heather in forum Advanced JavaReplies: 4Last Post: 02-11-2009, 09:58 AM -
creating jar file
By po0oker in forum Advanced JavaReplies: 3Last Post: 04-04-2008, 07:49 PM -
creating .ear file
By psn in forum Enterprise JavaBeans (EJB)Replies: 1Last Post: 01-06-2008, 05:01 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks