-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 Hyder,
On 2/8/15 11:28 PM, Hyder Hashmi wrote: > When I execute the following code in my project folder, it creates > the file in my current folder(project folder). > > import java.io.File; public class CreateFile{ File f = null; try{ f > = new File("test.txt"); bool = f.createNewFile(); > System.out.println("File created: "+bool); }catch(Exception e){ > e.printStackTrace(); } } > > I am now calling this class in my servlet. The servlet is executing > perfectly on the tomcat, however, the file is getting created in > the tomcat's bin folder instead of my project folder placed in the > webapps. > > If I specify the path, then it creates the file on that location , > however, that will be hardcoding and will not work on the other > computer. 1. Use ServletContet.getRealPath("/path/inside/webapp"). 2. Don't ever use ServletContext.getRealPath The reason you shouldn't use getRealPath is because your web application might not be deployed in an "unexploded" WAR file, and therefore getRealPath will return null in that case, so you won't be able to do anything with that path. Instead, you need to use some other mechanism for writing files. What do you plan to do with these files once they have been written? If you intend to serve them back to clients using Tomcat's DefaultServlet, that usually ends badly due to resource-caching, etc. We have some servlets that write files to the filesystem for auditing purposes. We have a configuration file that specifies where those files should be written, and we load that file on startup. Perhaps reading from a configuration file, or even from the servlet's init-params, you can build a correct filesystem path and write your files there. - -chris -----BEGIN PGP SIGNATURE----- Version: GnuPG v1 Comment: GPGTools - http://gpgtools.org iQIcBAEBCAAGBQJU2MzTAAoJEBzwKT+lPKRYV08QAIam6R7sR9c1YmPgkkuqEYM2 xoGUzcfnR6AFbRhTwu95W1k+yxHUqV+zaq6+z9ULBjXKVEO+0VS55EL9CTwDW1Xb p64zP1zOdGq2pGJswIwj4voq94ZKQPKp6HK3hnuaA1RsskRY2Wvi7eiwskbw5KNi AWI4iYHkJGQySUc5HnwwNLoZYqcpO7q5p91b/2Pk3r2g1hGBFZFM4KOHGfEjRgOH VOUZnXmUEeJ7vIiOfbmJmvIZL/mBRdlzulVA7ID9JbiJs3id/WdzLun0Eh/DNnaX ur1mhL+tZpuE+xy6WgkPAfMqkkzJ8R4jkn7c0YJZX+rmdHDJYj0WgjVYq53nBrMG ogd3QHE32SesB6JCabveas57dQTLO6cykBMKZ7kWOkS1t+GNjemPWUKUIdpFb+pM jqBOuXOOgRUPtqGO7b83B7QJILz1JvyCWHsfNzbnqi1WB/98AT2F0KrquNWOpJLF IIGNBrpdeIh0Wlr8t5ZmOr806hnItWEHB1pqwCvBXok2jbllZrBaC+OqwloWah09 V3IfyHJKvux7BNA83SSK+wpHAYR2W7Esn1lYdxqmxYv4q4FqPbvATgnYVfR6wwVu WD4nQVgNQl2CReDiT53SnQK6xKPMtCYYIa0jYybtB+0xNjKz3aemSW82JYvs+oj+ 5qye5crH7bGxRs4cI09g =LeVi -----END PGP SIGNATURE----- --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org For additional commands, e-mail: users-h...@tomcat.apache.org