TransWikia.com

Processing of a file: byte arrays and dimentions

Stack Overflow Asked by ld420 on December 25, 2021

Hello i have a file which i am reading via ByteArrayInputStream. I have to keep track of the byte that are left to read because i need to put that information in relation to a progress bar that will be added later on.

Before putting the byte array referred to the file into the stream i am calculating its lenght in bytes. Every time i process a line from the input stream i am also calculating it’s lenght in bytes and comparing it to the whole lenght. As you can see from the code below i am saving this ratio inside the variable newValue via a setter. That value represents a percentage that tells me at which point the process is.

The problem is that that value never reaches 100 but stops at 97(96.9). I debugged the whole thing and noticed that the value passed never reaches exactly the value tot but only approaches it in a way that the newValue approaches to 100 without reaching it. Does anybody have an explanation?

Here the code:

private String fName =""; // this is where i save the file name
    private byte[] docData = new byte[] {}; // this is where i store file data

public void printAndProcess() {
        
        InputStream is = null; 
        BufferedReader bfReader = null;
        try {
            is = new ByteArrayInputStream(getDocData());
            bfReader = new BufferedReader(new InputStreamReader(is));
            String temp = null;
            int tot = getDocData().length;
            int passed = 0; 
            while((temp = bfReader.readLine()) != null){
                passed += temp.getBytes().length;
                setNewValue((double) (passed*100)/tot);
                System.out.println(temp);
               
                
            }
            System.out.println(getNewValue());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(is != null) is.close();
            } catch (Exception ex){
                 
            }
        }
        
    }

The file (Name + Data) has been saved via a Servlet which i am leaving it for completeness:

public class UpServlet extends HttpServlet
{

    private static final long serialVersionUID = -4057880812848897784L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        System.out.println("IN GET");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        System.out.println("IN POST");
        try
        {

            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (int ix = 0; ix < items.size(); ix++)
            {
                FileItem item = (FileItem) items.get(ix);
                if (!item.isFormField())
                {
                    String fName = item.getName();
                    if (fName.indexOf("\") > 0) fName = fName.substring(fName.lastIndexOf("\") + 1, fName.length()); 
                    InputStream filecontent = item.getInputStream();

                    if (request.getSession().getAttribute("myController") != null)
                    {
                        MyController myController = (MyController) request.getSession().getAttribute("myController");
                        myController.setfName(fName);
                        myController.setDocData(readFully(filecontent));
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public static byte[] readFully(InputStream stream) throws IOException  
    {
        byte[] buffer = new byte[8192];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int bytesRead;
        while ((bytesRead = stream.read(buffer)) != -1)
        {
            baos.write(buffer, 0, bytesRead);
        }
        return baos.toByteArray();
    }

}

2 Answers

temp.getBytes().length gives you the length of the string. Every line in the file has the newline character (or characters) at the end, but the string you have read doesn't contain those characters. So you don't add them up to the passed.

A better approach would be to keep track of the current position on the stream. Check out answers to this question for ideas: Given a Java InputStream, how can I determine the current offset in the stream?

Answered by Sergei on December 25, 2021

BufferedReader 's readLine() will discard end of line characters (n and r).

Try not to encapsulate your inputstream in readers , which are made for reading text (character streams) .

Answered by Arnaud on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP