Search code examples
javastreamwriter

How to get length of a stream writer in java


In java is there any functionality equivalent to below c# code for getting stream length.

StreamWriter.BaseStream.Length

I have searched on internet and also I checked the properties of "BufferredWriter", "OutputStreamWriter" and "FileOutputStream" but I did not find anything. Any information is appreciated.

Thank you so much.


Solution

  • Finally I had to use File.length() property as I found no way to get length from stream like C#.

    Here is how it was done:

    Note (using flag etc.) which file the stream is associated with.

    When you need the length of stream, just get File.Length for the file which you had associated with stream like below.

    Why I needed to check length is to prevent writing to file more than defined max length.

                    String sFilePath = this.m_sLogFolderPath + File.separator;
                    if(this.m_File2Active == true)
                    {
                        sFilePath += Def.DEF_FILE2;
                    }
                    else
                    {
                        sFilePath += Def.DEF_FILE1;
                    }
                    File file = new File(sFilePath);
                    if(file.length() > this.m_lMaxSize)
                    {
                        this.m_bwWriter.flush();
                        this.m_bwWriter.close();
                        this.m_bwWriter = null;
                        sFilePath = this.m_sLogFolderPath + File.separator;
                        if (this.m_File2Active == true)
                        {
                            sFilePath += Def.DEF_FILE1;
                            this.m_File2Active = false;
                        }
                        else
                        {
                            sFilePath += Def.DEF_FILE2;
                            this.m_File2Active = true;
                        }
                        this.m_bwWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sFilePath, true), Def.DEF_ENCODING_UTF8));
                    }