I can not create a binary file.

src/main/java src/main/resources 

For example, the resources are application.properties and I get it so

 InputStream is = getClass().getClassLoader().getResourceAsStream("application.properties"); 

But how to write to the same directory file? I do so.

 FileOutputStream fos = new FileOutputStream("Files.bin"); ObjectOutputStream serial = new ObjectOutputStream(fos); serial.writeObject(filesFound); serial.flush(); fos.close(); serial.close(); 

But nothing happens and no file where there is.

    1 answer 1

    Try to create a file this way, the path to the file is displayed in the bottom of the console.

      File file = new File ("Files.bin"); FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream serial = new ObjectOutputStream(fos); serial.writeObject(filesFound); serial.flush(); fos.close(); serial.close(); System.out.println("Путь к созданному файлу: " + file.getAbsolutePath()); 

    Addition, in order to be able to get the file from the application running in Tomcat, I used this method:

     @ResponseBody @RequestMapping(method = RequestMethod.GET) public String method(HttpServletRequest request) { File file = null; try { ServletContext context = request.getSession().getServletContext(); String realContextPath = context.getRealPath(request.getContextPath()); System.out.println("realContextPath" + realContextPath); file = new File(realContextPath + "/WEB-INF/Files.bin"); //это маленький колстыль, чтоб можно было запускать из иде и в томкате if (!file.isFile()) { realContextPath = context.getRealPath(""); file = new File(realContextPath + "/WEB-INF/Files.bin"); } //тут можем работать с file System.out.println("Files.bin is found = " + file.isFile()); } catch (Exception e) { e.printStackTrace(); } return "hello"; } 
    • I tried it, it creates it in c: \ eclipse. Ie in ide. And with a project in which directory it can create a file? WEB-INF / classes? - Kleimosc
    • Watching where the deployment is, if it's a Tomkat, then TOMCAT_HOME/bin - MrFylypenko
    • Well, at least so. In general, how can I point to resources? Not prescribing the absolute path - Kleimosc
    • @Kleimosc, have you tried an example from here? link first example. In the string new FileOutputStream("config.properties"); replace with new FileOutputStream("src/main/resources/Files.bin"); - CheshireK
    • Updated the answer, try it. @CheshireK Your option will not work, because The application runs in the Tomcat container, not in the main. - MrFylypenko