import java.io.*; @RestController public class hello { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() throws IOException { /* * I/0 demo *读取本地text.txt文件,在页面显示 */ String result = null; //指定读取的文件 File f = new File("text.txt"); FileInputStream fis = null; try { fis = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); result = line; } System.out.flush(); br.close(); isr.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
图
图
代码可以优化吗?
System.out.println(line);
result = line;
=====>
System.out.println(line);
result += line;
显示是显示了。
没见过这么写的, 你从哪向页面输出的...
从项目root
代码有的自己写,有的参考的。
现在解决了,但需优化...
package com.progress.progress; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.io.*; @RestController public class hello { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() throws IOException { /* * I/0 demo * */ String result = ""; //指定读取的文件 File f = new File("text.txt"); FileInputStream fis = null; try { fis = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); result += line + "<br>"; } br.close(); isr.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
@Coca-code: 除了字符串加 改成stringbuilder, 其他可以了