相关疑难解决方法(0)

java有效地获取文件大小

谷歌搜索时,我发现使用java.io.File#length()可能很慢. FileChannel有一个size()方法也可用.

在java中有一种有效的方法来获取文件大小吗?

java filesize

161
推荐指数
6
解决办法
21万
查看次数

Spring MVC @PathVariable被截断了

我有一个控制器,提供对信息的RESTful访问:

@RequestMapping(method = RequestMethod.GET, value = Routes.BLAH_GET + "/{blahName}")
public ModelAndView getBlah(@PathVariable String blahName, HttpServletRequest request,
                            HttpServletResponse response) {
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,如果我使用带有特殊字符的路径变量命中服务器,它将被截断.例如: http:// localhost:8080/blah-server/blah/get/blah2010.08.19-02:25:47

参数blahName将是blah2010.08

但是,对request.getRequestURI()的调用包含传入的所有信息.

知道如何防止Spring截断@PathVariable吗?

java rest spring get spring-mvc

135
推荐指数
7
解决办法
7万
查看次数

应该在HttpServletResponse.getOutputStream()/.getWriter()上调用.close()吗?

我用谷歌搜索找不到权威的答案.在Java servlet中,可以通过response.getOutputStream()或response.getWriter()访问响应主体.应该在写入之后在此流上调用.close()吗?

一方面,Blochian劝告总是关闭输出流.另一方面,我认为在这种情况下不存在需要关闭的底层资源.套接字的打开/关闭在HTTP级别进行管理,以允许诸如持久连接之类的事情.

java servlets outputstream

90
推荐指数
4
解决办法
5万
查看次数

使用spring MVC返回生成的pdf

我正在使用Spring MVC.我必须编写一个服务,它将从请求体中获取输入,将数据添加到pdf并将pdf文件返回给浏览器.使用itextpdf生成pdf文档.我怎么能用Spring MVC做到这一点.我试过用这个

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public Document getPDF(HttpServletRequest request , HttpServletResponse response, 
      @RequestBody String json) throws Exception {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
    OutputStream out = response.getOutputStream();
    Document doc = PdfUtil.showHelp(emp);
    return doc;
}
Run Code Online (Sandbox Code Playgroud)

showhelp生成pdf的函数.我暂时将一些随机数据放在pdf中.

public static Document showHelp(Employee emp) throws Exception {
    Document document = new Document();

    PdfWriter.getInstance(document, new FileOutputStream("C:/tmp/report.pdf"));
    document.open();
    document.add(new Paragraph("table"));
    document.add(new Paragraph(new Date().toString()));
    PdfPTable table=new PdfPTable(2);

    PdfPCell cell = new PdfPCell (new Paragraph ("table"));

    cell.setColspan (2);
    cell.setHorizontalAlignment (Element.ALIGN_CENTER);
    cell.setPadding (10.0f);
    cell.setBackgroundColor (new BaseColor (140, 221, 8));                                  

    table.addCell(cell);                                    
    ArrayList<String[]> …
Run Code Online (Sandbox Code Playgroud)

java spring response spring-mvc itext

56
推荐指数
1
解决办法
10万
查看次数

从Spring Boot中的resources文件夹中读取文件

我正在使用Spring Boot和json-schema-validator.我正在尝试读取jsonschema.json从该resources文件夹调用的文件.我尝试了几种不同的方法,但我无法让它发挥作用.这是我的代码.

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);
Run Code Online (Sandbox Code Playgroud)

这是文件的位置.

在此输入图像描述

在这里,我可以在文件classes夹中看到该文件.

在此输入图像描述

但是当我运行代码时,我得到以下错误.

jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json (No such file or directory)
Run Code Online (Sandbox Code Playgroud)

我在代码中做错了什么?

java spring spring-boot json-schema-validator

45
推荐指数
11
解决办法
11万
查看次数

在Spring MVC 3.1控制器的处理程序方法中直接流到响应输出流

我有一个控制器方法来处理ajax调用并返回JSON.我正在使用json.org的JSON库来创建JSON.

我可以做以下事情:

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String getJson()
{
    JSONObject rootJson = new JSONObject();

    // Populate JSON

    return rootJson.toString();
}
Run Code Online (Sandbox Code Playgroud)

但是将JSON字符串放在一起是有效的,只是让Spring将它写入响应的输出流.

相反,我可以将它直接写入响应输出流,如下所示:

@RequestMapping(method = RequestMethod.POST)
public void getJson(HttpServletResponse response)
{
    JSONObject rootJson = new JSONObject();

    // Populate JSON

    rootJson.write(response.getWriter());
}
Run Code Online (Sandbox Code Playgroud)

但似乎有一个更好的方法来做到这一点,而不是诉诸于传递HttpServletResponse给处理程序方法.

是否有另一个类或接口可以从我可以使用的处理程序方法返回,以及@ResponseBody注释?

spring spring-mvc httpresponse

21
推荐指数
1
解决办法
3万
查看次数

在Spring中从Controller返回一个文件

我是新来的春天.我有一个带有RequestMapping的控制器,用于多个GET参数.他们返回一个字符串.但是一种方法需要在"/ res /"文件夹中返回一个文件.我怎么做?

@RequestMapping(method = RequestMethod.GET,value = "/getfile")
public @ResponseBody 
String getReviewedFile(@RequestParam("fileName") String fileName)
{
    return //the File Content or better the file itself
}
Run Code Online (Sandbox Code Playgroud)

谢谢

spring spring-mvc

9
推荐指数
2
解决办法
3万
查看次数

如何使用rest模板下载图像?

我有以下代码:

restTemplate.getForObject("http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg", File.class);
Run Code Online (Sandbox Code Playgroud)

我特别拍摄了不需要授权的图片,绝对适用于所有人.

下面的代码执行时,我看到以下stacktrace:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.io.File] and content type [image/jpeg]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:559)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:243)
    at com.terminal.controller.CreateCompanyController.handleFileUpload(CreateCompanyController.java:615)
Run Code Online (Sandbox Code Playgroud)

我错了什么?

java spring get http resttemplate

9
推荐指数
3
解决办法
2万
查看次数

如何在 Spring RestController 中下载 excel 文件

我正在使用 Apache POI 生成.xlsx文件。

我想从 Spring 控制器返回该文件。这是我到目前为止所做的:

控制器:

@RequestMapping(method = RequestMethod.GET)
    public HttpEntity<byte[]> createExcelWithTaskConfigurations(HttpServletResponse response) throws IOException {
        byte[] excelContent = excelService.createExcel();

        HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=my_file.xls");
        header.setContentLength(excelContent.length);

        return new HttpEntity<>(excelContent, header);
    }
Run Code Online (Sandbox Code Playgroud)

是否可以从 rest 控制器返回实际的 excel 文件,以便用户可以将其下载到他的计算机上?至于现在控制器返回 byte[] 但我想返回它的实际文件。我怎样才能做到这一点?

java excel spring

9
推荐指数
1
解决办法
2万
查看次数

Spring Rest Web服务将文件作为资源返回

我正在尝试从服务器上部署的Rest Web服务返回文件流,并在客户端上从Rest Web服务处理此流.在服务器上我使用此代码:

@Override
@RequestMapping(value = "/file", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) 
public @ResponseBody Resource getAcquisition(@RequestParam(value="filePath", required = true) String filePath) throws FileNotFoundException{
    // acquiring the stream
    File file= new File(filePath);
    InputStream stream = new FileInputStream(file);
    // counting the length of data
    final long contentLength = file.length() ;

    return new InputStreamResource(stream){
        @Override
        public long contentLength() throws IOException {
            return contentLength;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

而且,此刻,在客户端我使用它(然后我必须在文件系统上写文件)

@Override
public void getFile(String serverIp, String toStorePath, String filePath) throws Exception{
    RestTemplate restTemplate = new …
Run Code Online (Sandbox Code Playgroud)

java rest spring file spring-mvc

6
推荐指数
1
解决办法
1万
查看次数