Efficient way to write InputStream to a File in Java 6

后端 未结 3 681
忘掉有多难
忘掉有多难 2021-02-15 02:52

I will get input stream from third party library to my application. I have to write this input stream to a file.

Following is the code snippet I tried:

p         


        
相关标签:
3条回答
  • 2021-02-15 02:56

    It can get cleaner with an OutputStreamWriter:

    OutputStream outputStream = new FileOutputStream("output.txt");
    Writer writer = new OutputStreamWriter(outputStream);
    
    writer.write("data");
    
    writer.close();
    

    Instead of writing a string, you can use a Scanner on your inputStream

    Scanner sc = new Scanner(inputStream);
    while (sc.HasNext())
        //read using scanner methods
    
    0 讨论(0)
  • 2021-02-15 03:14

    Since you are stuck with Java 6, do yourself a favour and use Guava and its Closer:

    final Closer closer = Closer.create();
    final InputStream in;
    final OutputStream out;
    final byte[] buf = new byte[32768]; // 32k
    int bytesRead;
    
    try {
        in = closer.register(createInputStreamHere());
        out = closer.register(new FileOutputStream(...));
        while ((bytesRead = in.read(buf)) != -1)
            out.write(buf, 0, bytesRead);
        out.flush();
    } finally {
        closer.close();
    }
    

    Had you used Java 7, the solution would have been as simple as:

    final Path destination = Paths.get("pathToYourFile");
    try (
        final InputStream in = createInputStreamHere();
    ) {
        Files.copy(in, destination);
    }
    

    And yourInputStream would have been automatically closed for you as a "bonus"; Files would have handled destination all by itself.

    0 讨论(0)
  • 2021-02-15 03:18

    If you're not on Java 7 and can't use fge's solution, you may want to wrap your OutputStream in a BufferedOutputStream

    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream("xx.txt"));
    

    Such buffered output stream will write bytes in blocks to the file, which is more efficient than writing byte per byte.

    0 讨论(0)
提交回复
热议问题