java stream to file code example

Example 1: write input stream to file java

InputStream pdf = // greate some input stream data
try (FileOutputStream outputStream = new FileOutputStream(new File("/Users/kirkbrown/documents/my.pdf"))) {

			int read;
			byte[] bytes = new byte[1024];

			while ((read = pdf.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}
		}

Example 2: java stream write to file

@Test
public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() 
  throws IOException {
    FileWriter fileWriter = new FileWriter(fileName);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Some String");
    printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
    printWriter.close();
}

Tags:

Java Example