Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
One thing I've sometimes wondered is which is the better style out of the two shown below (if any)? Is it better to return immediately if a guard condition hasn't been satisfied, or should you only do the other stuff if the guard condition is satisfied? For the sake of argument, please assume that the guard condition is a simple test that returns a boolean, such as checking to see if an elemen...
What is a stream in the programming world ? Why do we need it ? Kindly explain with the help of an analogy, if possible.
I'm updating some old code to grab some binary data from a URL instead of from a database (the data is about to be moved out of the database and will be accessible by HTTP instead). The database API seemed to provide the data as a raw byte array directly, and the code in question wrote this array to a file using a BufferedOutputStream. I'm not at all familiar with Java, but a bit of googling ...
A webpage contains a link to an executable (i.e. If we click on the link, the browser will download the file on your local machine). Is there any way to achieve the same functionality with Java? Thank you
The following method only writes out the latest item I have added, it does not append to previous entries. What am I doing wrong? public void addNew() { try { PrintWriter pw = new PrintWriter(new File("persons.txt")); int id = Integer.parseInt(jTextField.getText()); String name = jTextField1.getText(); String surname = jTextField2.get...
I want to save in a text file without overwriting the current data. I mean the next data that will be save will go to the new/next line whenever I save and that is my problem, I don't know how to do that. Could someone help me about this matter? Here's the code in save() method : public void save(String filename) throws IOException { FileOutputStream fOut = new FileOutputStream(filename...
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.
If I have a file, and I want to literally write '42' to it (the value, not the string), which for example is 2a in hex, how do I do it? I want to be able to use something like outfile.write(42) or outfile.write(2a) and not write the string to the file. (I realize this is a simple question but I can't find the answer of google, probably because I don't know the correct search terms)
I googled for this for a while but can't seem to find it and it should be easy. I want to append a CR to then end of an XML file that I am creating with a Transformer. Is there a way to do this> I tried the following but this resulted in a blank file? Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "file:///ReportW...
I'm having trouble getting a bit to work properly in java6...I'm trying to write a compression program that will write bits to a compressed file...so for example a common letter such as "e" might just be the binary sequence "101" in ascii I think the fileOutputStream.write(int) method is what I'm going to want to accomplish this, but how to I represent a sequence of bits as in int?
I am attempting to Store() the change made to my application's Properties. The .Properties file is located in 'resources' package, which is different from the package that contains my UI and model. I opened the package using: this.getClass().getClassLoader().getResourceAsStream("resources/settings.properties") Is there a functional equivalent of this that permits me to persist changes to th...
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 am using FileOutputStream for writing some data to a file. Every time I execute my program, it appends the data to existing file instead of creating new one. I want to create a new file every time I execute the program. How do I do that?
With Java: I have a byte[] that represents a file. How do I write this to a file (ie. C:\myfile.pdf) I know it's done with InputStream, but I can't seem to work it out.
Is there a way to get the file name from a FileOutputStream or from FileInputStream?
I am looking for some confirmation that FileOutputStream works like I think it does. I am downloading a file and, if I lose the network connection, trying to resume the download from where it left off. How I am trying to do this is to open the FileOutputStream as not appending and then writing nothing at an offset. My question is will that work or does opening it as non appending delete th...
I have a FloatBuffer of known size and just want to dump the data to a file (in binary) for inspection outside my app. What's the easiest way to do this?
import java.io.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; public class CreatXMLFile { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); // System.out.print("Enter number to add elements in your ...
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...
How do I append to large files efficiently. I have a process that has to continually append to a file and as the file size grows the performance seems to slow down as well. Is there anyway to specify a large buffer size with the append
I'm writing a game in which user can create his own level and remove them also. The only trouble is that I want files to be saved with names as level1, level2, level3 etc without asking user name of level. While saving a game with level5 name it might be possible that any previous level with that name already exists. Is there any way to avoid such problems. I mean before saving the name by whi...
  /*
   * 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 file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

Author(s):
Arthur van Hoff
Since:
JDK1.0
See also:
File
FileDescriptor
FileInputStream
 
 public
 class FileOutputStream extends OutputStream
 {
    
The system dependent file descriptor. The value is 1 more than actual file descriptor. This means that the default value 0 indicates that the file is not open.
 
     private FileDescriptor fd;
 
     private FileChannel channelnull;
 
     private boolean append = false;
 
     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 an output file stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.

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

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

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

    
Creates an output file stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.

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

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Parameters:
name the system-dependent file name
append if true, then bytes will be written to the end of the file rather than the beginning
Throws:
FileNotFoundException if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
java.lang.SecurityException if a security manager exists and its checkWrite method denies write access to the file.
Since:
JDK1.1
See also:
java.lang.SecurityManager.checkWrite(java.lang.String)
    public FileOutputStream(String nameboolean append)
        throws FileNotFoundException
    {
        this(name != null ? new File(name) : nullappend);
    }

    
Creates a file output stream to write to the file represented by the specified File object. A new FileDescriptor object is created to represent this file connection.

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

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Parameters:
file the file to be opened for writing.
Throws:
FileNotFoundException if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
java.lang.SecurityException if a security manager exists and its checkWrite method denies write access to the file.
See also:
File.getPath()
java.lang.SecurityException
java.lang.SecurityManager.checkWrite(java.lang.String)
    public FileOutputStream(File filethrows FileNotFoundException {
        this(filefalse);
    }

    
Creates a file output stream to write to the file represented by the specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.

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

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Parameters:
file the file to be opened for writing.
append if true, then bytes will be written to the end of the file rather than the beginning
Throws:
FileNotFoundException if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
java.lang.SecurityException if a security manager exists and its checkWrite method denies write access to the file.
Since:
1.4
See also:
File.getPath()
java.lang.SecurityException
java.lang.SecurityManager.checkWrite(java.lang.String)
    public FileOutputStream(File fileboolean append)
        throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
         = new FileDescriptor();
        .incrementAndGetUseCount();
        this. = append;
        if (append) {
            openAppend(name);
        } else {
            open(name);
        }
    }

    
Creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.

First, if there is a security manager, its checkWrite method is called with the file descriptor fdObj argument as its argument.

Parameters:
fdObj the file descriptor to be opened for writing
Throws:
java.lang.SecurityException if a security manager exists and its checkWrite method denies write access to the file descriptor
See also:
java.lang.SecurityManager.checkWrite(java.io.FileDescriptor)
    public FileOutputStream(FileDescriptor fdObj) {
        SecurityManager security = System.getSecurityManager();
        if (fdObj == null) {
            throw new NullPointerException();
        }
        if (security != null) {
            security.checkWrite(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 a file, with the specified name, for writing.

Parameters:
name name of file to be opened
    private native void open(String namethrows FileNotFoundException;

    
Opens a file, with the specified name, for appending.

Parameters:
name name of file to be opened
    private native void openAppend(String namethrows FileNotFoundException;

    
Writes the specified byte to this file output stream. Implements the write method of OutputStream.

Parameters:
b the byte to be written.
Throws:
IOException if an I/O error occurs.
    public native void write(int bthrows IOException;

    
Writes a sub array 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 void writeBytes(byte b[], int offint lenthrows IOException;

    
Writes b.length bytes from the specified byte array to this file output stream.

Parameters:
b the data.
Throws:
IOException if an I/O error occurs.
    public void write(byte b[]) throws IOException {
        writeBytes(b, 0, b.length);
    }

    
Writes len bytes from the specified byte array starting at offset off to this file output stream.

Parameters:
b the data.
off the start offset in the data.
len the number of bytes to write.
Throws:
IOException if an I/O error occurs.
    public void write(byte b[], int offint lenthrows IOException {
        writeBytes(bofflen);
    }

    
Closes this file output stream and releases any system resources associated with this stream. This file output stream may no longer be used for writing bytes.

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 FD use count associated with the channel
             * The use count is incremented whenever a new channel
             * is obtained from this stream.
             */
            .decrementAndGetUseCount();
            .close();
        }
        /*
         * Decrement 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 file descriptor associated with this stream.

Returns:
the FileDescriptor object that represents the connection to the file in the file system being used by this FileOutputStream object.
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 output stream.

The initial position of the returned channel will be equal to the number of bytes written to the file so far unless this stream is in append mode, in which case it will be equal to the size of the file. Writing bytes to this stream will increment the channel's position accordingly. Changing the channel's position, either explicitly or by writing, will change this stream's file position.

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

    
Cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream.

Throws:
IOException if an I/O error occurs.
See also:
FileInputStream.close()
    protected void finalize() throws IOException {
        if ( != null) {
            if ( == . ||  == .) {
                flush();
            } else {
                /*
                 * 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(.);
                }
            }
        }
    }
    private native void close0() throws IOException;
    private static native void initIDs();
    static {
        initIDs();
    }
New to GrepCode? Check out our FAQ X