1. 程式人生 > >Java原始碼詳解之FileOutputStream

Java原始碼詳解之FileOutputStream

Java原始碼詳解之FileOutputStream

1.類定義

A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream

(or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

一個把資料寫到一個File或者到一個FileDescriptor的檔案輸出流。無論檔案是否可用,或者是否可被建立,取決於底層的平臺。尤其是在某些平臺上,一次只允許一個 FileOutputStream(或者其它的檔案寫物件) 開啟檔案進行寫入。 在這樣的情況下,如果涉及的檔案已經開啟,那麼這個類的構造器將會執行失敗。

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

FileOutputStream 是用於寫諸如圖片資料等原始位元組流。如果要寫字元流,請考慮使用 FileWriter

2. 實戰程式碼

將圖片儲存在如下的資料夾中。
在這裡插入圖片描述

  • getConnection(String url)
 //get connection with specific url
public InputStream getConnection(String url) { //01.CloseableHttpClient is a abstract class CloseableHttpClient httpClient = HttpClients.createDefault(); //use get HttpGet httpGet = new HttpGet(url); httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:63.0) Gecko/20100101 Firefox/63.0"); InputStream inputStream =null; try { //get the request's response CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); //get the InputStream of entity inputStream = entity.getContent(); } catch (IOException e) { e.printStackTrace(); } return inputStream; }
  • getImageName()
 //this part,use a customed method,rather than a specific path to store new file
    public String getImageName(){
        String imageName ;
        Date date = new Date();
        //DateFormat dateFormat = DateFormat.getDateInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        //System.out.println(simpleDateFormat.format(date));
        imageName = dirPath+simpleDateFormat.format(date) + ".jpg";
        return imageName;
    }
  • writeImageInDisk(InputStream inputStream)
public void writeImageInDisk(InputStream inputStream){
        String fileAddress = getImageName();
        File newFile = new File(fileAddress);

        //使用位元組儲存圖片,但是這裡的大小隻有1024B = 1kB,是否會導致陣列溢位?
        byte [] image = new byte[1024] ;

        int length ;
        FileOutputStream fileOutputStream = null;
        try {
            if(inputStream!=null){
                fileOutputStream = new FileOutputStream(newFile);
                while((length = inputStream.read(image))!=-1){
                    fileOutputStream.write(image,0,length);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

執行結果如下:
在這裡插入圖片描述