Java Question Create a file from InputStream

barx

Well-Known Member
Licensed User
Longtime User
Does this code look like the right way to create a file from an InputStream??

B4X:
    /**
     * Gets a File from an Asset
     *
     */
    public void GetFileFromAsset(Asset asset, final String TargetDir, final String TargetFilename) {
        if (asset == null) {
            throw new IllegalArgumentException("Asset cannot be null");
        }
       
        PendingResult<DataApi.GetFdForAssetResult> pendingResult = Wearable.DataApi.getFdForAsset(mGoogleApiClient, asset);
        pendingResult.setResultCallback(new ResultCallback<DataApi.GetFdForAssetResult>() {
            @Override
            public void onResult(DataApi.GetFdForAssetResult result) {
                try {
                    InputStream assetInputStream = result.getInputStream();
                    OutputStream assetOutputStream = new FileOutputStream(File.Combine(TargetDir, TargetFilename));
                   
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                   
                    while((bytesRead = assetInputStream.read(buffer)) != -1) {
                        assetOutputStream.write(buffer, 0, bytesRead);
                    }
                   
                    assetInputStream.close();
                    assetOutputStream.flush();
                    assetOutputStream.close();
                } catch (IOException e) {
                    BA.Log(e.toString());
                }           
            }
        });
    }

Thanks
 

barx

Well-Known Member
Licensed User
Longtime User
I prefer this method:
B4X:
InputStream in = ...
OutputStream out = ...
anywheresoftware.b4a.objects.streams.File.Copy2(in, out);
out.close();


Well that seems a lot simpler, so I think I will prefer that method too ;)
 
Top