簡體   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