Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
What is a stream in the programming world ? Why do we need it ? Kindly explain with the help of an analogy, if possible.
Is there any kind of difference between 1) DocumentBuilder.parse(InputStream) and 2) DocumentBuilder.parse(InputSource)? I could only find that for the first case, the parser detects the encoding from the stream so it is safer while in the latter I am not sure if it is required to set the encoding. Any other points (e.g. performance) I should be aware? Thanks
I've got a Writer program that writes one line of text to a file, then waits until the user hits return before it writes another line and then exits. Only after that is the file closed. The code: public class Writer { Writer() { } public static String[] strings = { "Hello World", "Goodbye World" }; public static void main(String[] ar...
I'm using a third-party commercial library which seems to be leaking file handles (I verified this on Linux using lsof). Eventually the server (Tomcat) starts getting the infamous "Too many open files error", and I have to re-start the JVM. I've already contacted the vendor. In the meantime, however, I would like to find a workaround for this. I do not have access to their source code. Is ...
The default output of File.toURL() is file:/c:/foo/bar These don't appear to work on windows, and need to be changed to file:///c:/foo/bar Does the format file:/foo/bar work correctly on Unix (I don't have a Unix machine to test on)? Is there a library that can take care of generating a URL from a File that is in the correct format for the current environment? I've considered using a ...
All, I have written a PhoneBook application in Java that is command line based. The application basically asks for some details of user like Name, Age, Address and phone numbers and stores them in a file. Other operations involve looking up PhoneBook by name, phone number etc. All the details are entered through console. I am trying to write JUnit test cases for each of the functionalities th...
I have a file that contains java serialized objects like "Vector". I have stored this file over Hadoop Distributed File System(HDFS). Now I intend to read this file (using method readObject) in one of the map task. I suppose FileInputStream in = new FileInputStream("hdfs/path/to/file"); wont' work as the file is stored over HDFS. So I thought of using org.apache.hadoop.fs.FileSystem class. ...
I have a file that contains some amount of plain text at the start followed by binary content at the end. The size of the binary content is determined by some one of the plain text lines I read. I was using a BufferedReader to read the individual lines, however it exposes no methods to refer to read a byte array. The readUTF for a DataInputStream doesnt read all the way to the end of the line,...
Dear all, I want to acqeuire a lock on a file when threo read gets started on a specific file ,so that no other application can read the file which has been already locked and want to release the lock file when thread terminates.
is the close() method of Closable interface gets called while the Closable object is garbage collected ? [in java 6.0] I have a static variable which is a resource(database connection). Since this is a static resource, there's no correct place to call the close() explicitly.
Suppose my input file contains: 3 4 5 6 7 8 9 10 I want to run a while loop and read integers, so that I will get 3,4,5,6,7,8 and 10 respectively after each iteration of the loop. This is really simple to do in C/C++ but not in Java... I tried this code: try { DataInputStream out2 = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); ...
in my FileInputStream I get a FileNotFoundException, but I know he file exists, I can download it with the webbrowser. It also works if I copy the Link from the exception to webbrowser. Rights are on RWX to everyone for testing, but this doesn't help. there are no special signs in the filename... I have no idea why this fails.. thx 4 help! EDIT: KeyStore ts = KeyStore.getInstance("PKCS12")...
How to get InputStream and size of File type in servlet? Previously i was using FileUpload type which has getInputStream() and getSize() methods, but now i have to use File type for bulk upload. I have tried but File type has no such methods.
The following code works, but takes way too long (over a minute) to open a small file. The LogCat shows a lot of instances of "GC_FOR_MALLOC freed #### objects / ###### bytes in ##ms". Any suggestions? File dirPath = new File(Environment.getExternalStorageDirectory(), "MyFolder"); String content = getFile("test.txt"); public String getFile(String file){ String content = ""; try { Fi...
I am working on sound processing with the use of Java now. Within my project, I have to deal with the stream. So I have a lot of staffs to do with DataLine and OutputStream or InputStream. But to me, they are too similar:( Is there someone who can help me with this question? Thanks in advance! Here are some code I used : TargetDataLine line; ByteArrayOutputStream out = new By...
i want to save a lot of binary data files(pdf, images, office docs...) into one single "blob" file. now i'm not sure what is better, saving stuff with java Serializable and save things to disc or to use a database like sqlite to make things happen. or is there a third, maybe better way? my question is, how well do those methods perform in terms of access speed and data-integrety. in this one si...
This is a newbie question, I know. Can you guys help? I'm talking about big files, of course, above 100MB. I'm imagining some kind of loop, but I don't know what to use. Chunked stream? One thins is for certain: I don't want something like this (pseudocode): File file = new File(existing_file_path); byte[] theWholeFile = new byte[file.length()]; //this allocates the whole thing into memory ...
I'm having trouble on where to begin performing this task, I'd like some examples or input on how I should set up my server/client components to receive and send data including letting the client download images. Here's my client-side code: package V3; import java.io.*; import java.net.*; public class Version3Client { public static void main(String[] args) throws IOException { ...
I am writing a Java servlet, using Tomcat as the container, which creates and serves PDF files to the end-user. Currently the PDF files are created in-memory and written out as a response to a POST. I would like to change this up somewhat so that the PDF files are written to disk (so they can be served up again later). I am having trouble locating a suitable "how-to" for doing this. How can I...
How can I read a file to bytes in Java? It is important to note that all the bytes need to be positive, i.e. the negative range cannot be used. Can this be done in Java, and if yes, how? I need to be able to multiply the contents of a file by a constant. I was assuming that I can read the bytes into a BigInteger and then multiply, however since some of the bytes are negative I am ending up w...
Guys i have a file which has only one line. The file has no encoding it is a simple text file with single line. For every 2048 byte in a line , there is new record of 151 byte (totally 13*151 byte = 1945 records + 85 byte empty space). similarly for the next 2048 bytes. What is the best file i/o to use? i am thinking of reading 2048 bytes from file and storing it in an array . while (offse...
  /*
   * Copyright 1994-2007 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.io;
 
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

Author(s):
Arthur van Hoff
Since:
JDK1.0
See also:
File
FileDescriptor
FileOutputStream
 
 public
 class FileInputStream extends InputStream
 {
     /* File Descriptor - handle to the open file */
     private FileDescriptor fd;
 
     private FileChannel channel = null;
 
     private Object closeLock = new Object();
     private volatile boolean closed = false;
 
     private static ThreadLocal<BooleanrunningFinalize =
                                 new ThreadLocal<Boolean>();
 
     private static boolean isRunningFinalize() {
         Boolean val;
         if ((val = .get()) != null)
             return val.booleanValue();
         return false;
     }

    
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkRead method is called with the name argument as its argument.

If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

Parameters:
name the system-dependent file name.
Throws:
FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
java.lang.SecurityException if a security manager exists and its checkRead method denies read access to the file.
See also:
java.lang.SecurityManager.checkRead(java.lang.String)
 
     public FileInputStream(String namethrows FileNotFoundException {
         this(name != null ? new File(name) : null);
     }

    
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkRead method is called with the path represented by the file argument as its argument.

If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

Parameters:
file the file to be opened for reading.
Throws:
FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
java.lang.SecurityException if a security manager exists and its checkRead method denies read access to the file.
See also:
File.getPath()
java.lang.SecurityManager.checkRead(java.lang.String)
    public FileInputStream(File filethrows FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
         = new FileDescriptor();
        .incrementAndGetUseCount();
        open(name);
    }

    
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.

If there is a security manager, its checkRead method is called with the file descriptor fdObj as its argument to see if it's ok to read the file descriptor. If read access is denied to the file descriptor a SecurityException is thrown.

If fdObj is null then a NullPointerException is thrown.

Parameters:
fdObj the file descriptor to be opened for reading.
Throws:
java.lang.SecurityException if a security manager exists and its checkRead method denies read access to the file descriptor.
See also:
java.lang.SecurityManager.checkRead(java.io.FileDescriptor)
    public FileInputStream(FileDescriptor fdObj) {
        SecurityManager security = System.getSecurityManager();
        if (fdObj == null) {
            throw new NullPointerException();
        }
        if (security != null) {
            security.checkRead(fdObj);
        }
         = fdObj;
        /*
         * FileDescriptor is being shared by streams.
         * Ensure that it's GC'ed only when all the streams/channels are done
         * using it.
         */
        .incrementAndGetUseCount();
    }

    
Opens the specified file for reading.

Parameters:
name the name of the file
    private native void open(String namethrows FileNotFoundException;

    
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.
Throws:
IOException if an I/O error occurs.
    public native int read() throws IOException;

    
Reads a subarray as a sequence of bytes.

Parameters:
b the data to be written
off the start offset in the data
len the number of bytes that are written
Throws:
IOException If an I/O error has occurred.
    private native int readBytes(byte b[], int offint lenthrows IOException;

    
Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

Parameters:
b the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
Throws:
IOException if an I/O error occurs.
    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }

    
Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.

Parameters:
b the buffer into which the data is read.
off the start offset in the destination array b
len the maximum number of bytes read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
Throws:
java.lang.NullPointerException If b is null.
java.lang.IndexOutOfBoundsException If off is negative, len is negative, or len is greater than b.length - off
IOException if an I/O error occurs.
    public int read(byte b[], int offint lenthrows IOException {
        return readBytes(bofflen);
    }

    
Skips over and discards n bytes of data from the input stream.

The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. If n is negative, an IOException is thrown, even though the skip method of the InputStream superclass does nothing in this case. The actual number of bytes skipped is returned.

This method may skip more bytes than are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file.

Parameters:
n the number of bytes to be skipped.
Returns:
the actual number of bytes skipped.
Throws:
IOException if n is negative, if the stream does not support seek, or if an I/O error occurs.
    public native long skip(long nthrows IOException;

    
Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks.

Returns:
an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking.
Throws:
IOException if this file input stream has been closed by calling close or an I/O error occurs.
    public native int available() throws IOException;

    
Closes this file input stream and releases any system resources associated with the stream.

If this stream has an associated channel then the channel is closed as well.

Throws:
IOException if an I/O error occurs.
Revised:
1.4
Spec:
JSR-51
    public void close() throws IOException {
        synchronized () {
            if () {
                return;
            }
             = true;
        }
        if ( != null) {
            /*
             * Decrement the FD use count associated with the channel
             * The use count is incremented whenever a new channel
             * is obtained from this stream.
             */
           .decrementAndGetUseCount();
           .close();
        }
        /*
         * Decrement the FD use count associated with this stream
         */
        int useCount = .decrementAndGetUseCount();
        /*
         * If FileDescriptor is still in use by another stream, the finalizer
         * will not close it.
         */
        if ((useCount <= 0) || !isRunningFinalize()) {
            close0();
        }
    }

    
Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.

Returns:
the file descriptor object associated with this stream.
Throws:
IOException if an I/O error occurs.
See also:
FileDescriptor
    public final FileDescriptor getFD() throws IOException {
        if ( != nullreturn ;
        throw new IOException();
    }

    
Returns the unique FileChannel object associated with this file input stream.

The initial position of the returned channel will be equal to the number of bytes read from the file so far. Reading bytes from this stream will increment the channel's position. Changing the channel's position, either explicitly or by reading, will change this stream's file position.

Returns:
the file channel associated with this file input stream
Since:
1.4
Spec:
JSR-51
    public FileChannel getChannel() {
        synchronized (this) {
            if ( == null) {
                 = FileChannelImpl.open(truefalsethis);
                /*
                 * Increment fd's use count. Invoking the channel's close()
                 * method will result in decrementing the use count set for
                 * the channel.
                 */
                .incrementAndGetUseCount();
            }
            return ;
        }
    }
    private static native void initIDs();
    private native void close0() throws IOException;
    static {
        initIDs();
    }

    
Ensures that the close method of this file input stream is called when there are no more references to it.

Throws:
IOException if an I/O error occurs.
See also:
close()
    protected void finalize() throws IOException {
        if (( != null) &&  ( != .)) {
            /*
             * Finalizer should not release the FileDescriptor if another
             * stream is still using it. If the user directly invokes
             * close() then the FileDescriptor is also released.
             */
            .set(.);
            try {
                close();
            } finally {
                .set(.);
            }
        }
    }
New to GrepCode? Check out our FAQ X