InputStream and OutputStream

Introduction

  • InputStream: to get the data from the source and read the data

  • OutStream: to create a output and write the data into the output

Type

  • BufferedSteam, DataStream, FileStream, PipeStream

Example

  • Copy the data from existing file to the new output file

		FileInputStream is = new FileInputStream("test.txt");
		// 1024 byte = 1kb
		byte [] b = new byte[1024];
		
		// Create new File 
		try(FileOutputStream os = new FileOutputStream( new File("test2.txt"))){
				// read the data file from the source and put it into b
				while ((is.read(b)) != -1){
		    // Write the data b into output , and each time of the size is 1kb
					os.write(b);
				}
				// Handle the remaining data
				os.flush();
		    // os.close();
		}
		catch(IOException e){
				throw e;
		}
  • Copy the data from existing file to the new output file ( File as a payload of api)

@GetMapping("/file")
public String file(HttpServletResponse response) throws IOException {
    // Define the attachment
    response.setHeader("Content-Disposition", "attachment; filename=" + "test2.txt");
    // Define the output source which is come from the response of api
    try(BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream())) {
        FileInputStream is = new FileInputStream("test.txt");
        byte[] b = new byte[1024];
        while ((is.read(b)) != -1){
			    os.write(b);
		    }
    }
    catch (IOException e){
        System.out.println(e.getMessage());
    }
    return "file";
}

References

Last updated

Was this helpful?