Here you can find the source of saveFile(String filename, byte[] content)
public static void saveFile(String filename, byte[] content) throws IOException
//package com.java2s; /* /*w w w . j a v a2s .com*/ * Licensed to the soi-toolkit project under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The soi-toolkit project licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { public static void saveFile(String filename, byte[] content) throws IOException { saveFile(filename, new ByteArrayInputStream(content)); } public static void saveFile(String filename, InputStream inputStream) throws IOException { File file = createFileWithUniqueName(filename); copy(inputStream, file); System.err.println("### Wrote attachement to file: " + file.getAbsolutePath()); } public static File createFileWithUniqueName(String orgFilename) throws IOException { File file = new File(orgFilename); // Bail out if no conflict, the a file with this filename doesn't exist already if (!file.exists()) return file; // Find out a unique name... int fileTypeIdx = orgFilename.lastIndexOf('.'); String filename = orgFilename; String fileType = ""; if (fileTypeIdx >= 0) { fileType = filename.substring(fileTypeIdx); // Let the fileType include the leading '.' filename = filename.substring(0, fileTypeIdx); } for (int i = 0; file.exists(); i++) { file = new File(filename + '-' + i + fileType); } return file; } public static byte[] copy(InputStream src) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(src, baos); return baos.toByteArray(); } public static void copy(InputStream src, File dst) throws IOException { copy(src, new FileOutputStream(dst)); } public static void copy(InputStream src, OutputStream dst) throws IOException { try { // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = src.read(buf)) > 0) { dst.write(buf, 0, len); } } finally { if (src != null) { src.close(); } if (dst != null) { dst.flush(); dst.close(); } } } }