user15381310
user15381310

Reputation:

How to convert OutputStream to String in Java (Android)?

I am trying to read the string that I get inside an outputStream that in turn is written there by a ftp - from a ftp server.

I'm stuck at this problem for about 2 hours and I find it hard to belive that it's so difficult to solve.

Is there any nice solution for my problem?

Here's the relevant code:

boolean success = false;
        OutputStream outputStream = null;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName));
            success = ftp.retrieveFile("/ViatorAndroid/" + fileName, outputStream);
        } catch (Exception e) {
            Log.d("FTPDownloadLatestVersion", "e = " + e.getMessage() + " " + Arrays.toString(e.getStackTrace()));
        }
        outputStream.close();
        if (success) {
            
            String versionNumberString = outputStream.getString(); // ??? I need here a way to get the string inside this output stream. Any clue how???
            int versionNumber = Integer.parseInt(versionNumberString);
            Log.d("FTPGetLastestVersionCode", "VersionNumber = " + versionNumber);
            return BuildConfig.VERSION_CODE < versionNumber;
        }

Upvotes: 0

Views: 2243

Answers (1)

JP Moresmau
JP Moresmau

Reputation: 7403

If you just want the content in a string, you build a ByteArrayOutputStream that will collect all the bytes written to it, and then turn this into a String.

Something like

try (ByteArrayOutputStream baos=new ByteArrayOutputStream()){
    boolean success = ftp.retrieveFile("/ViatorAndroid/" + fileName, baos);
    if (success){
       String versionNumberString = new String(baos.toByteArray(),StandardCharsets.UTF_8);
       ...
    }
}

Upvotes: 1

Related Questions