3

I have an object, in this object I have an InputStream which contains a file.

I want to write what is inside of InputStream to a file inside of a folder.

How would I go about doing this in Core Java?

I was able to print out each line of the InputStream using BufferedReader and .readLine(), however I want the entire file wrote to disk not just what is inside of it.

Hopefully this makes sense, thank you.

k1308517
  • 213
  • 3
  • 12

2 Answers2

9

If you are using Java 7 or above you can use java.nio.file.Files:

InputStream in = obj.getInputStrem();
Path file = ...;
Files.copy(in, path);

It also supports different options (see CopyOption implementations like StandardCopyOption and LinkOption)

vsminkov
  • 10,912
  • 2
  • 38
  • 50
2

Pretty sure its out there already, you could google it. But as you asked about writing to a file inside of a folder, assuming the InputStream variable is named "input":

FileOutputStream output = null;
try {
    // Create folder (if it doesn't already exist)
    File folder = new File("<path_to_folder>\\<folder_name>");
    if (!folder.exists()) {
        folder.mkdirs();
    }
    // Create output file
    output = new FileOutputStream(new File(folder, "<file_name>"));
    // Write data from input stream to output file.
    int bytesRead = 0;
    byte[] buffer = new byte[4096];
    while ((bytesRead = input.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
} catch (IOException ioex) {
    ioex.printStackTrace();
} finally {
    try {
        if (output != null) {
            output.close();
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    // Also close InputStream if no longer needed.
    try {
        if (input != null) {
            input.close();
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
}
  • Will that write everything include file icon etc... or just the contents of the file? I did google but I was getting confused by it all, I have not asked a question on here for months. – k1308517 Aug 15 '16 at 22:41
  • It will write everything including icon, however: the `` must include extension for the icon to appear eg for a text file, "`mytextfile.txt`" or for a mp3 audio file, "`song.mp3`" etc. – Usman Shahid Amin Aug 15 '16 at 22:47
  • Also, `` eg `C:\\Users\\\\Desktop` and `` eg `MyFolder` – Usman Shahid Amin Aug 15 '16 at 22:59