FileInputStream read()

Hi Guys,
The value of -1 returned from the FileInputStream's read() method indicates the end of file.
But what if the file being read has "-1" in it ?
thanks
V

The ReadInt method "Returns: the next four bytes of this input stream, interpreted as an int."
It assumes that the 4 bytes are a valid int (they will be if you're doing things correctly), and an int can have a value of -1, so it can't use that value as EOF.
If you learn how signed/negative numbers are represented at the bit-level, this will make sense to you. Do a search for "two's complement arithmetic", which is how it's done.

Similar Messages

  • FileInputStream.read()  and non-blocking file i/o

    According to the API, FileInputStream.read() is :
    public native int read() throws IOException
    Reads a byte of data from this input stream. This method blocks if no input is yet available.
    Returns:
    the next byte of data, or -1 if the end of the file is reached.In what instances does the read() blocks? Is there a danger that the call to read() would block forever?

    thanks martian!
    is the ff code right enough to prevent i/o blocking?
      FileInputStream fis = new FileInputStream(src);
      FileOutputStream fos = new FileOutputStream(sPersistorFolder+src.getName());
      if(fis.available() > 0) {
        int c = -1;
        while((c=fis.read()) != -1) {
          fos.write(c);
      fis.close();
      fos.close();

  • FileInputStream.read returning negative values

    I'm trying to read binary data from a file and convert it to decimal. If I use a hex editor, through one section, I'll see the values as they actually are. Using read() on a FileInputStream object seems to randomly create negative values which are sometimes correct if I use Math.abs(), and sometimes theyre not. I don't have a clue what's going on and it's getting frustrating, as FileInputStream.read() supposedly returns an integer between 0 ane 255, which is what I'm expecting.
    Thanks for the help!

    Are you doing something like this...
    byte value = in.read();
    int useIt = value;If the value is being stored in a byte and then cast to an int, the sign bit will be extended and it will become negative. This is because a java byte is actualy +/- 127.
    To solve it, you do this..
    int useIt = value & 0xff;or never store it as a byte in the first place.
    This is what you have to do when reading bytes out of byte arrays...
    int useIt = byteArray[index] & 0xff;

  • FileInputStream read problem

    Hi!
    I have a problem with reading a byte[] buffer from a file using the FileInputStream:
    ----- code example -----
    File = new FileInputStream(filename);
    data = new byte[File.available()];
    File.read(data);
    String test = new String(data);
    ----- end example -----
    So, when I print the bytes of the array "data", some chars are strange (negative numbers).
    When I convert the byte array into a string, some of the ASCII codes of the string's chars are wrong (like 65533).
    What can I do?

    It totally depends on what kind of data you're trying to read in choosing between a reader and an input stream. If you're reading binary data (like an image), use the input stream and read bytes. If you're trying to read character data, use a reader:BufferedReader reader = new BufferedReader (new FileReader ("test.txt"));
    String line;
    while ((line = reader.readLine ()) != null) {
        // process line
    }Kind regards,
      Levi

  • FileInputStream read bytes how to get String

    FileInputStream in = new InputStream("text.out");
    while ((numRead = in.read(buf)) >= 0)
    System.out.println(numRead);
    This prints the bytes of contents....
    if i wan to get the contents of text.out(still using FileInputStream )
    in string, how do i go it
    Alicia

    If you know it's a textfile, the recommend way to read it is using a FileReader instead of a FileInputStream. If you wrap the FileReader in a BufferedReader, you can also easily read it line by line (the lines are returned as Strings).

  • FileInputStream.read() return of -1

    FileInputStream will return a -1 upon hitting the end of a given file. otherwise, it returns the value of the byte it reads in. I was wondering what happens when the value of the byte it reads in is -1. in he case of the following code, wouldn't the -1 byte being returned be misinterpreted to mean EOF?
    while(( myInt  = myFileInputStream.read() ) != -1)
      // Do stuff
    }

    that's why it's returning an int instead of a byte
    int -1 != 255
    int -1 = #FFFFFFFF

  • READING FILE IN BINARY DATA

    Any body could suggest code fragment to read the file contents in Binary format? -In JSP?.

    Yeah, you'll have to be a bit more specific... what exactly do you want to do with the data? If you just want to get the data from a binary file (like an image or something) a byte at a time, then you can use a FileInputStream.

  • How do I know how many bytes it has read so far ?

    Like in a FileInputStream.read(byte [] b) method. How do I know how many bytes have been read into b so far ? Thanks!

    You can't directly as the method block, however it return the number of bytes that could be read. To achieve what you want I would create a wrapper class that would override read(byte[] b) and process it byte by byte with:
    int size = b.length;
    for(int i = 0; i < length; i++)
        int r = wrapped.read();
        if( r != -1 )
            b[i] = (byte)r;
            readSoFar++;
    }

  • Reading Txt File into a GUI

    Hi,
    Direction on how to read a text file consisting of rows and columns with 1's and 0's into a GUI would be useful.
    I can ask user for filename and display the file in a DOS window but unsure of how I would use a text box to ask for a filename and then display the contents of it into the GUI.
    Im fairly new to Java, Where do I start?
    Thanks.

    Alternatively, take a look at this:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class Editor extends JFrame
        private BorderLayout borderLayout1 = new BorderLayout();
        private JScrollPane jScrollPane1 = new JScrollPane();
        private JTextArea jTextArea1 = new JTextArea();
        private JMenuBar jMenuBar1 = new JMenuBar();
        private JMenu jMenu1 = new JMenu();
        private JMenuItem jMenuItem1 = new JMenuItem();
        private JMenuItem jMenuItem2 = new JMenuItem();
        public static void main(String[] args)
            Editor editor=new Editor();
            editor.setBounds(100,100,400,400);
            editor.setVisible(true);
        public Editor()
            try
                jbInit();
            catch(Exception e)
                e.printStackTrace();
            this.pack();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private void jbInit() throws Exception
            this.getContentPane().setLayout(borderLayout1);
            this.setJMenuBar(jMenuBar1);
            jMenu1.setText("File");
            jMenuItem1.setText("Open");
            jMenuItem1.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(ActionEvent e)
                    jMenuItem1_actionPerformed(e);
            jMenuItem2.setText("Save");
            jMenuItem2.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(ActionEvent e)
                    jMenuItem2_actionPerformed(e);
            this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
            jScrollPane1.getViewport().add(jTextArea1, null);
            jMenuBar1.add(jMenu1);
            jMenu1.add(jMenuItem1);
            jMenu1.add(jMenuItem2);
        void jMenuItem1_actionPerformed(ActionEvent e)
            JFileChooser fileSelectDialog=new JFileChooser();
            fileSelectDialog.setDialogTitle("Open file");
            fileSelectDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileSelectDialog.setCurrentDirectory(new File("."));
            int result=fileSelectDialog.showDialog(this, null);
            if(result==fileSelectDialog.APPROVE_OPTION)
                File file=fileSelectDialog.getSelectedFile();
                if(file!=null)
                    try
                        FileInputStream fileInputStream=new FileInputStream(file);
                        byte[] data=new byte[(int)file.length()];
                        fileInputStream.read(data);
                        jTextArea1.setText(new String(data));
                    catch(IOException ex)
                        showExceptionMessage(ex);
        void jMenuItem2_actionPerformed(ActionEvent e)
            JFileChooser fileSelectDialog=new JFileChooser();
            fileSelectDialog.setDialogTitle("Save file");
            fileSelectDialog.setDialogType(JFileChooser.SAVE_DIALOG);
            fileSelectDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileSelectDialog.setCurrentDirectory(new File("."));
            int result=fileSelectDialog.showDialog(this, null);
            if(result==fileSelectDialog.APPROVE_OPTION)
                File file=fileSelectDialog.getSelectedFile();
                if(file!=null)
                    try
                        FileOutputStream fileOutputStream=new FileOutputStream(file,false);
                        fileOutputStream.write(jTextArea1.getText().getBytes());
                    catch(IOException ex)
                        showExceptionMessage(ex);
        public void showExceptionMessage(Exception ex)
            StringWriter stringWriter=new StringWriter();
            PrintWriter printWriter=new PrintWriter(stringWriter);
            ex.printStackTrace(printWriter);
            JOptionPane.showMessageDialog(this,stringWriter.toString().replace('\t',' ').replace('\r',' '),"Exception!",JOptionPane.ERROR_MESSAGE);
    }

  • Fileinputstream problem in session bean

    Hi i m using fileInputStream in Seesion bean to read one file. but i want to give relative path of that file according to ear. but it give me fileNotFound Exception.. i cant give physical path of that file.. the file i m trying to read exists in the ear..
    can u help me out?
    Venky

    I have read some good number of XMLs and property files. Make use of Class.getResourceAsStream()method by passing the file name as argument. From the InputStream construct FileInputStream.

  • IndexOutOfBoundsException  from FIS.read() method

    I am trying to read 8 bytes from a FIS
    According to the API for this method I should be able to read bytes 3 - 11 by using an offset of 3 and a length of 8 which is what
    fin.read(l_data_array, i_offset, i_length); is supposed to do but if my offset is >0 then it fails.
    Any ideas what is wrong?
    ( My file is approx 3KB so this is not the prob and the first method call does read 8 bytes )
        byte [] x = readBytesFromFile(0, 8); //ok
        byte [] x = readBytesFromFile(3, 8); //IndexOutOfBoundsException  thrown
       private byte [] readBytesFromFile( int i_offset, int i_length){
          byte[] l_data_array = new byte[i_length];
          try {
             File fd = new File(m_db);
             FileInputStream fin = new FileInputStream(fd);
             fin.read(l_data_array, i_offset, i_length);
             fin.close();
          catch (FileNotFoundException fnf) {
             System.out.println("File not found Exception");
          catch (IOException ioe) {
             System.out.println("IO Exception");
          return l_data_array;
       }error :
    java.lang.IndexOutOfBoundsException
         at java.io.FileInputStream.readBytes(Native Method)
         at java.io.FileInputStream.read(FileInputStream.java:194)
         at Rule109_Automation_Package.Rule_109_Processor.readBytesFromFile(Rule_109_Processor.java:224)

    Thanks for the replies folks.
    The file I will be reading in will, for the first part of the development phase, serve as a a Database. So it is liable to become > 1MB.
    Each record will be 1KB long, stored sequentially. So you are saying that if I want to read record No 999 I have to have a byte [] which can hold 999 * 1000 bytes. Seems a waste of resources ( Even though temporary ) that I can't move a pointer along the FIS and read say, bytes 9,000 to 10,000 into an array like ( byte[1000] ) instead of needing an array like ( byte [10,000] )
    What kind of kinky reason do sun have for this?

  • Java.io.FileInputStream.readBytes() IOException: insufficient resources

    I am getting this strange error
    "IOException: Insufficient system resources exist to complete the requested service"
    Complete stack trace is
    java.io.IOException: Insufficient system resources exist to complete the requested service
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(Unknown Source)
    at org.apache.http.entity.InputStreamEntity.writeTo(InputStreamEntity.java:85)
    at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:127)
    at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:253)
    at org.apache.http.impl.conn.AbstractClientConnAdapter.sendRequestEntity(AbstractClientConnAdapter.java:218)
    at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:249)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:124)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:483)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
    And the code that uses this input stream only uses a buffer of size 2K. Here is the code
    private final static int BUFFER_SIZE = 2048;
    byte[] buffer = new byte[BUFFER_SIZE];
    while ((l = instream.read(buffer)) != -1) {
    outstream.write(buffer, 0, l);
    What could be causing this "Insufficient Resource" error???

    That is an OS error.
    Googling for that error provides possible reasons for it.

  • Best way to read a file

    Hi All,
    I'm curious to know what is the best (fast) way to read a binary file. In particular, I'm thinking if using a BufferedInputStream I can obtain better results.
    In my opinion the FileInputStream class should be already optimized to read bytes from the underlying OS so that using BufferedInputStream I should not have benefits.
    If this is true, FileInputStream.read() should have the same performances of FileInputStream.read(byte[]).
    Is it correct ?
    ste

    what I expect for 1 is the FileOutputStream collects all bytes in a buffer calling OS when the buffer is full or if flush() is called. I don't think all the difference (30s vs 100ms) is since method invocations overhead.That's not what it does. It has no built in buffer, as far as I am aware.
    I created this test to test the cost of method overhead. This is using read(), but could be changed to use write. It shows definite performance effects to doing single reads repeatedly on a 5 meg byte array input stream (as opposed to one read) but nothing that's going to compare to reading latency from an actual file
         public static void readTest() {
              byte[] vals = new byte[5000000];
              for (int i = 0; i < vals.length; i++) {
                   vals[i] = (byte)(i % 256);
              ByteArrayInputStream in = new ByteArrayInputStream(vals);
              long time1 = System.currentTimeMillis();
              for (int i = 0; i < vals.length; i++) {
                   in.read();
              long time2 = System.currentTimeMillis();
              in = new ByteArrayInputStream(vals);
              try {
                   int got = in.read(new byte[5000000]);
                   System.out.println("got: " + got);
              catch (IOException iox) {
                   iox.printStackTrace();
              long time3 = System.currentTimeMillis();
              System.out.println("read each: " + (time2 - time1));
              System.out.println("read batch: " + (time3 - time2));
         }

  • How to delete a file on web server without using FTP

    Hi All
    I hv given a facility to a site user to upload some files..
    And an interface to web administrator to view all the files..
    I want to know how can i write a code in JSP which allow the web administrator to delete any of that file which is not of his/her interest through provided interface only.
    OR
    Is it possible to delete a particular file from web server without getting login into FTP account
    Thanx

    new File(strFileName).remove;
    Simply as this.
    Don't forget to import java.io.FileInputStream.

  • The dialog box open twice when open file from the server

    I use the following code to download/open file from the server:
    <%
    String filename = "MengxianhuiDocTest.doc";
    String filepath = "D:\\";
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition",
    ??attachment; filename=\"" + filename + "\"");
    java.io.FileInputStream fileInputStream =
    new java.io.FileInputStream(filepath + filename);
    int i;
    while ((i=fileInputStream.read()) != -1) {
    out.write(i);
    fileInputStream.close();
    out.close();
    %>
    If the application runs, the Open or Save dialog box display.When I select open the file,
    the dialog box will display twice.
    Pls help me.
    Thanks.

    thx
    but I tried it and it did't work.
    The dialog box also display twice.

Maybe you are looking for

  • Classic report search

    Hi everybody, to say it first, I'm a newbie to apex because my lack of experience with it. I've to create an application that searches for keywords inside textfields of a table using instant search(I'm using the clarifit plugin for that). Therefore I

  • Multiselect,checkbox,shuffle in a report

    ID:, NAME: 1, FIRST 2, SECOND report has: select multiselect_field ID from table -- 1:2 If I use a multiselect,checkbox,shuffle in a report it shows the ID# of the record.. but I want to show the name that is stored in the table the LOV is using.. ho

  • Titler program causes cs5 premium pro to crash

    I was in the middle of a project using cs5 premium pro and using titler with no problems.  There was a momentary power outage (don't know if this had anything to do with the problem) and computer rebooted without issue.  Next day when I went to use t

  • Read message content in ABAP reporting

    Hi, We need to read the message payload content for reporting purposes. I suppose this data is contained in tables SXMSCLUP and SXMSCLUR. (field CLUSTD) The problem is that the content is in LRAW type. Do you know how to convert this type to get a co

  • ConnectToTCPServer Failure in Windows7

    I am using "Measurement Studio Version 6.0, Labwindows/CVI" for my TcpIP Server and Client Program. It works very well in the Windows XP circumstance using below functions.  But the function ConnectToTCPServer fails with error message like below, whe