繁体   English   中英

如何在 Java Dynamic WebService 应用程序中写入本地文件?

[英]How to write to a local file in a Java Dynamic WebService application?

我有一个包含 json 数据Books.json的文件。 该文件位于com.ebook.database包中。 我可以成功读取文件的内容,但是当我尝试写入文件时,我收到FileNotFoundException

下面是我的项目结构,显示了Books.json文件所在的包: 在此处输入图片说明

下面是我用来成功读取文件内容的代码( filePath接收一个字符串值/com/ebook/database/Books.json并读取文件就好了:

/**
     * A utility method for reading the data stored in a json file.
     * 
     * @param filePath path to the desired database table 
     * @return the contents of the desired table
     * @throws IOException occurs when the desired file is not found
     */
    public static String readFile(String filePath) throws IOException {
        InputStream inputStream = DBHelper.class.getResourceAsStream(filePath);
        String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        return content;
    }

下面是我用来尝试访问相同Books.json文件进行写入的代码, Books.json成功:

/**
     * Adds a new Book to the Books.json file
     * */
    public void postBook(Book book, String filePath) {
        
        //create Gson instance with pretty-print
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        
        //First, convert the Product object into a Json string
        try {
               
            File file = new File(filePath);
            OutputStream out = new FileOutputStream(file);
            
            /* This logic will check whether the file
               * exists or not. If the file is not found
               * at the specified location it would create
               * a new file*/
              if (!file.exists()) {
                 file.createNewFile();
              }
            
               List<Book> books;
               String updatedBooksJson;
               
               //if file is empty, just throw the object in -- no prior comma needed.      
               if(DBHelper.tableIsEmpty(filePath)) {
                   books = new ArrayList<Book>();
                   books.add(book);
                   
                   updatedBooksJson = gson.toJson(books);
                   
                   //writing to the file.
                   byte[] bytes = updatedBooksJson.getBytes();
                   out.write(bytes[6]);
                   out.flush();
                    
               } else {
                   //The file is not empty.  Read the list of Products currently
                   //in the file, convert to List<Product>, add the new Product, and
                   //update the file
                   
                   books = getAllBooks(filePath);
                   
                   //add the new product to the existing list of products:
                   books.add(book);
                   
                   //write the updated products list to the Products.json file
                   updatedBooksJson = gson.toJson(books);
                   
                   //clear the old file contents
                   FileChannel.open(Paths.get(filePath), StandardOpenOption.WRITE).truncate(0).close();
                      
                   //write the new file contents
                 //writing to the file.
                   byte[] bytes = updatedBooksJson.getBytes();
                   out.write(bytes[6]);
                   out.flush();
               }
               
               out.close();
            } catch (IOException e) {
                e.printStackTrace();
              }
    }

以下是尝试写入/com/ebook/database/Books.json文件时产生的/com/ebook/database/Books.json

INFO: Server startup in 2782 ms
java.io.FileNotFoundException: \com\ebook\database\Books.json (The system cannot find the path specified)
    at java.base/java.io.FileOutputStream.open0(Native Method)
    at java.base/java.io.FileOutputStream.open(FileOutputStream.java:292)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:235)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:185)
    at com.ebook.dal.BookDAO.postBook(BookDAO.java:59)
    at com.ebook.services.BookService.addNewBook(BookService.java:38)
    at com.ebook.resources.BookResource.postNewBook(BookResource.java:72)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:219)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:244)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:232)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:392)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:365)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:318)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:317)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:835)
Oct 11, 2020 3:32:40 PM org.apache.catalina.core.StandardContext reload

您在这里混合了类路径和本地文件系统路径。 你永远不应该在不知道你在做什么的情况下尝试覆盖类路径中的元素,因为这可能会在你重新启动应用程序时对它的行为产生影响。 只需将 放在文件系统上的某个地方,并在那里始终如一地读写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM