如何使用 Java 从真实文件中读取?

Posted

技术标签:

【中文标题】如何使用 Java 从真实文件中读取?【英文标题】:How do I use Java to read from a file that is real life? 【发布时间】:2021-12-03 16:29:59 【问题描述】:

我之所以使用 MultipartFile 是因为 swagger 中的图像中有一个按钮图像。我已成功将收到的 excel 文件中的值添加到数据库中,但同时遇到以下错误。

java.nio.file.NoSuchFileException: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@6417030b
    at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
    at sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:318)
    at sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:287)
    at java.nio.file.Files.move(Files.java:1395)
    at az.expressbank.expressbankproject.service.impl.UserDetailServiceImpl.acceptExcellFileAndInsertToDatabase2(UserDetailServiceImpl.java:62)
    at az.expressbank.expressbankproject.controller.UserDetailController.writeExcelledRowColumnIntoDatabase(UserDetailController.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

但另一个问题是,我无法将文件发送到我指定的文件夹。我想我已经关闭了所有东西,但我仍然无法将它发送到指定的文件夹,如果我发送它并修复我上面解释的错误,我的问题将不再存在。

 public Response acceptExcellFileAndInsertToDatabase2(MultipartFile file) throws IOException 
        String fileName = file.getOriginalFilename();
        if (fileName.substring(fileName.length() - 5, fileName.length()).equals(".xlsx")) 
            try (InputStream excelFile = file.getInputStream()) 
                String phoneNumber = "";
                String textMessage = "";
                Workbook workbook = WorkbookFactory.create(excelFile);
                Sheet sheet = workbook.getSheetAt(0);
                Iterator<Row> rowIt = sheet.rowIterator();
                while (rowIt.hasNext()) 
                    Row currentRow = rowIt.next();
                    Iterator<Cell> cellIterator = currentRow.iterator();
                    while (cellIterator.hasNext()) 
                        Cell currentCell = cellIterator.next();
                        if (currentCell.getCellTypeEnum() == CellType.NUMERIC) 
                            phoneNumber = NumberToTextConverter.toText(currentCell.getNumericCellValue());
                         else if (currentCell.getCellTypeEnum() == CellType.STRING) 
                            textMessage = String.valueOf(currentCell.getStringCellValue());
                        
                    
                
                UserDetail userDetail = new UserDetail();
                userDetail.setPhoneNumber(phoneNumber);
                userDetail.setTextMessage(textMessage);
                this.userDetailRepository.save(userDetail);
                excelFile.close();
                workbook.close();
                Path sourcePath = Paths.get(String.valueOf(file));
                Path targetPath = Paths.get("C:\\Users\\User\\Desktop\\ko\\" + sourcePath.getFileName());
                Files.move(sourcePath, targetPath);
                return new SuccessResponse(MessageCase.FILE_SUCCESSFULLY_WRITTEN_TO_DATABASE.getMessage(), 200);
             catch (IOException e) 
                e.printStackTrace();
            
        
        return new ErrorResponse(MessageCase.FAILED_HAPPEND_WHEN_FILE_WRITTEN_TO_DATABASE, 404);
    

【问题讨论】:

您的应用程序是网络应用程序吗?如果是这样,您希望用户先上传文件 (spring.io/guides/gs/uploading-files),然后您的应用可以在读取之前决定分配给它的本地文件路径/文件名,就像 @Lajos 指示的那样。 【参考方案1】:

您可以改为使用String path 参数。然后你可以这样做:

File file = new File(path);
FileInputStream excelFile = new FileInputStream(file);

【讨论】:

我不明白的是,比如说在查看页面部分,当用户按下添加文件按钮时,他发送到那里的文件类型应该是什么样的? Yani ben metodumun parametresinde tam olarak ne yazacağım, kısaca basit örnek göstere bilirmisin? @AnarMəmmədov 我们说的可能是Excel文件,所以应该是xls之类的。 是的,但是例如,如果你们中的任何人可以通过我的方法的简单示例简要地告诉我如何做到这一点,我会理解的。 @AnarMəmmədov 1. 将参数从file 重命名为路径, 2. 将FileInputStream excelFile = new FileInputStream(file); 移动到try 块中, 3. 将File file = new File(path); 的行放入try 块中作为第一行, 4. 将实际路径传递给您知道可以找到文件的方法。如果您没有这样做,请不要担心,在这种情况下您可以随时回到这里提出问题,但这些答案的目的是帮助您理解和解决您的问题,我们没有编写您的代码的目的。 ***.com/questions/69597565/…看到这个问题,这个问题我解释的很好。【参考方案2】:

问题可能是您在那里建立的这个无意义的targetPath

Path sourcePath = Paths.get(String.valueOf(file));
Path targetPath = Paths.get("C:\\Users\\User\\Desktop\\ko\\" + sourcePath.getFileName());

这可能已经失败了:

assertTrue(Files.exists(Paths.get("C:\\Users\\User\\Desktop\\ko\\")));

Files.exists(Path) 在不允许列出目录时也会返回false

【讨论】:

没错,当我把这些行放在注释行时,我不再收到任何错误,但现在还有一个问题,我想把收到的excel文件放在我的文件夹中电脑,我该怎么做? @Martin Zeitler @AnarMəmmədov 我不太确定 SpringBoot,但也可能是应用程序服务器不允许其根目录和/或指定存储设施之外的文件系统访问......和通常的做法是在尝试写入之前检查目录是否存在以及是否可写。 如果您能帮我在本网站上找到相关问题,我们将不胜感激。【参考方案3】:

最后,我成功解决了所有问题,一切正常。在这种情况下,我想做的是使用 MultipartFile 获取 excel 文件并将其中的值打印到数据库中的相应列,然后最难的就是把我从用户那里得到的excel文件分配到我在电脑上指定的文件夹中。

 @Override
    public Response acceptExcellFileAndInsertToDatabase2(MultipartFile file) throws IOException 
        System.out.println(file.getContentType());
        String fileName = file.getOriginalFilename();
        if (fileName.substring(fileName.length() - 5).equals(".xlsx")) 
            try (InputStream excelFile = file.getInputStream()) 
                String phoneNumber = "";
                String textMessage = "";
                Workbook workbook = new XSSFWorkbook(excelFile);
                Sheet datatypeSheet = workbook.getSheetAt(0);
                for (Row currentRow : datatypeSheet) 
                    for (Cell currentCell : currentRow) 
                        if (currentCell.getCellTypeEnum() == CellType.NUMERIC) 
                            phoneNumber = NumberToTextConverter.toText(currentCell.getNumericCellValue());
                         else if (currentCell.getCellTypeEnum() == CellType.STRING) 
                            textMessage = String.valueOf(currentCell.getStringCellValue());
                        
                    
                
                UserDetail userDetail = new UserDetail();
                userDetail.setPhoneNumber(phoneNumber);
                userDetail.setTextMessage(textMessage);
                this.userDetailRepository.save(userDetail);
                excelFile.close();

                String destination = "C:\\Users\\User\\Desktop\\ko\\"  + file.getOriginalFilename();
                File file1 = new File(destination);
                file.transferTo(file1);

                return new SuccessResponse(MessageCase.FILE_SUCCESSFULLY_WRITTEN_TO_DATABASE.getMessage(), 200);
             catch (IOException e) 
                e.printStackTrace();
            
        
        return new ErrorResponse(MessageCase.FAILED_HAPPEND_WHEN_FILE_WRITTEN_TO_DATABASE, 404);
    

【讨论】:

以上是关于如何使用 Java 从真实文件中读取?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 java 中使用 spark 从 AWS S3 读取 .xls 文件?并且无法读取 sheetName

如何使用 Java 直接从 Internet 读取文本文件?

如何在java中读取xep文件数据

如何在java中读取xep文件数据

java ArrayList 如何读取文件中的数据,并且搜索

如何从文件系统中读取 Java ObjectOutputStream 生成的文件?