0

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;
        }
3
  • Do you want the content in both the file and as a string? Commented May 7, 2021 at 13:20
  • No. I have the outputStream variable containing some kind of string. I need to have that content from that stream inside a string. Commented May 7, 2021 at 13:22
  • An output stream doesn't (normally) contain a string. It's a handle to "some place" that you can write stuff to. Unless that "some place" is explicitly a byte buffer or similar, it doesn't actually store what its written to. As an example: A FileOutputStream doesn't remember what you wrote to it. It simply writes it to a file and then forgets about it. You can construct a ByteArrayOutputStream where the "some place" is a byte array, but pretty much everything else is just a pointer to some other place. Commented May 7, 2021 at 13:27

1 Answer 1

1

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);
       ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.