1. 程式人生 > >對於src路徑問題,深層理解的實踐。且對於輸出流write()兩個方法的源碼閱讀。

對於src路徑問題,深層理解的實踐。且對於輸出流write()兩個方法的源碼閱讀。

nco != gpo del ppi 本地 thead name println

根據昨天的總結,可深層理解圖片中src的路徑。所以今天實現了一個想法。就是路徑寫入的是Controller,然後自動去本地找。

其實就是將電腦的本地圖片 顯示出來。通過輸出流的方式。

代碼如下:

@RequestMapping(value = "/img/{id}")
    public void img(@PathVariable(value = "id") String id,HttpServletResponse response) {
        File file = new File("D:\\img\\" + id + ".jpg");
        System.out.println(file);
        
try { InputStream inputStream = new FileInputStream(file); OutputStream outputStream = response.getOutputStream(); byte[] b = new byte[1024]; int a = -1; while ((a = inputStream.read(b)) != -1) { outputStream.write(b); System.
out.println(a); } response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("a.jpg", "UTF-8")); inputStream.close(); outputStream.flush(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); } }

可是無法正常顯示。發現打開的文件圖片大小為1kb,實際圖片為43kb。

最後發現了是輸出流寫的過程中,發生的錯誤。其實,就是方法的問題。

換成outputStream.write(b,0,a);就好了

所以接下來,我去讀一下write(Byte[]),和write(Byte[],0,length)兩個方法的區別。

  • write(byte b[])

public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }

所以可以看到,此方法內部調用的 write(b, 0, b.length);

可突然發現,重新用回write(byte b[])方法,依然好用。那我之前是見鬼了麽???

[○?`Д′? ○]

對於src路徑問題,深層理解的實踐。且對於輸出流write()兩個方法的源碼閱讀。