Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Please look through the below code, // A.java File file=new File("blah.txt"); FileWriter fwriter=new FileWriter(file); PrintWriter pwriter=new PrintWriter(fwriter); //B.java File file=new File("blah.txt"); FileWriter fwriter=new FileWriter(file); BufferedWriter bwriter=new BufferedWriter(bwriter); What is the difference between these two files? And when do we need to go for PrintWriter and ...
In a java program (java 1.5), I have a BufferedWriter that wraps a Filewriter, and I call write() many many times... The resulting file is pretty big... Among the lines of this file, some of them are incomplete... Do I need to call flush each time I write something (but I suspect it would be inefficient) or use another method of BufferedWriter or use another class...? (Since I've a zillion li...
Please Note: I am not "looking for teh codez" - just ideas for algorithms to solve this problem. This IS a homework assignment. I thought I was in the home stretch, about to finish it out, but the last part has absolutely stumped me. Never have I been stuck like this. It has to do with threading in Java. The Driver class reads a file, the first line indicates the number of threads, second lin...
I do some numerical calculation in Java, C# and C++. Some of them save a lot of data (to the text file). What is the fastest way to do it? C++. ofstream file; file.open(plik); for(int i=0;i<251;i++){ for(int j=0;j<81;j++) file<<(i-100)*0.01<<" "<<(j-40)*0.01<<" "<<U[i][j]<<endl; file<<endl; } Which I assume is very fast ( am I...
Possible Duplicate: In Java, what is the advantage of using BufferedWriter to append to a file? The site that I am looking at says "The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings." What make's it more efficient and why?
I need to write(append) huge string to flat file using java nio. The encoding is ISO-8859-1. Currently we are writing as shown below. Is there any better way to do the same ? public void writeToFile(Long limit) throws IOException{ String fileName = "/xyz/test.txt"; File file = new File(fileName); FileOutputStream fileOutputStream = new FileOutputStream(file, true); ...
I have a problem, which I do not seem to be able to solve... I do a http download of a file, but the CRC32 of the file on the server and on the client do not match. Also, the file has different size, so obviously I must be doing something wrong... when I download via Firefox, the filesize is ok... so I guess it is somewhere in the client code. I already found http://stackoverflow.com/questions...
What is the difference between newLine() and carriage return ("\r")? Which one is best to use? File f = new File(strFileGenLoc); BufferedWriter bw = new BufferedWriter(new FileWriter(f, false)); rs = stmt.executeQuery("select * from jpdata"); while ( rs.next() ) { bw.write(rs.getString(1)==null? "":rs.getString(1)); bw.newLine(); }
I am writing to a text file using a BufferedWriter but the BufferedWriter does not write to the file until the program I'm running is finished and I'm not sure how to update it as the BufferedWriter is supposedly writing. Here is some of my code that I have: FileWriter fw = null; try { fw = new FileWriter("C:/.../" + target + ".pscr",true); writer = new BufferedWriter(fw); writer....
So I have large (around 4 gigs each) txt files in pairs and I need to create a 3rd file which would consist of the 2 files in shuffle mode. The following equation presents it best: 3rdfile = (4 lines from file 1) + (4 lines from file 2) and this is repeated until I hit the end of file 1 (both input files will have the same length - this is by definition). Here is the code I'm using now but thi...
I'm looking at the following example Which uses the following code try { BufferedWriter out = new BufferedWriter(new FileWriter("outfilename")); out.write("aString"); out.close(); } catch (IOException e) {} What's the advantage over doing FileWriter fw = new FileWriter("outfilename"); I have tried both and they seem comparable in speed when it comes to the task of ...
I am creating a CSV file using BufferedWriter from a ResultSet object. A few of the database columns hold null values. When I call obj.write(rs.get()) I am getting a NullPointerException when the output is null. Is there any other class other than BufferedWriter which I can use to overcome this. I do not want to check for null condition on the database columns since there is large number of ...
I want to get data from the clipboard and store it in a .txt file. How do I create the .txt file? I have read a lot about getting data from a file but not the other way around. Here is my code: public void CallClipboard (){ System.out.println("Copying text from system clipboard."); String grabbed = ReadClipboard(); System.out.println(grabbed); } public S...
In all examples of a Java client/server, I've seen BufferedReader used for receiving data, like in BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); and PrintWriter for sending data, like in PrintWriter writer = new PrintWriter(socket.getOutputStream()); But can't I just use a BufferedWriter instead of a PrintWriter? I only need to send unformatt...
My question is about line (edit: 19), where the new PrintWriter is created with the constructor taking the FileWriter fw as a parameter. I don't understand the use of chaining the BufferedWriter bw to FileWriter if it isn't used later on in the actual writing. Can Java apply chaining in a way that bw still somehow affects the rest of the program? 16. try { 17. FileWriter fw...
FileInputStream reads all bytes of a file and FileOutputStream writes allbytes to a file which class do i use if i want to read all bytes of a file but line by line so that if fileA contains two lines line1 line2 then bytes of line1 and line2 are read seperately same goes for FileOutputStream
I have to fetch 500K rows from the database and write that data into the file , Means perform the I/O operation . I have done for two steps . Write each row one by one into the file . Make the chunk of those rows .Append those rows in StringBuffer and then print it . This one will be better but is there any way that File I/O can make the buffer on it's own without using StringBuffer . As this...
I have following sample CSV file rc,u,s,ui,gh m,1,8,0,12 n,3,0,0,7 d,1,1,8,0 I want to read this CSV file and get column by its name (e.g., s). subtract fetched column by some values and update that column in the CSV file. Is there an easy way to do it in Java?
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( new BufferedOutputStream( new FileOutputStream("out.txt") ) ) ); So let me see if I understand this: A byte output stream is opened for file "out.txt". It is then fed to a buffered output stream to make file operations faster. The buffered stream is fed to an output stream writer to bridge from bytes to characters. Finally, t...
i am writing program for chat room on client side i had wirtten clientSocket = new Socket('127.0.0.1',5432); socketInputBuffer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); socketOutputBuffer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); systemBuffer = new BufferedReader(new InputStreamReader(System.in)); and on server side sock ...
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
  /*
   * Copyright 1996-2005 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;


Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.

A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

 PrintWriter out
   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
 
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.

Author(s):
Mark Reinhold
Since:
JDK1.1
See also:
PrintWriter
FileWriter
OutputStreamWriter
 
 
 public class BufferedWriter extends Writer {
 
     private Writer out;
 
     private char cb[];
     private int nCharsnextChar;
 
     private static int defaultCharBufferSize = 8192;

    
Line separator string. This is the value of the line.separator property at the moment that the stream was created.
 
     private String lineSeparator;

    
Creates a buffered character-output stream that uses a default-sized output buffer.

Parameters:
out A Writer
 
     public BufferedWriter(Writer out) {
         this(out);
     }

    
Creates a new buffered character-output stream that uses an output buffer of the given size.

Parameters:
out A Writer
sz Output-buffer size, a positive integer
Throws:
java.lang.IllegalArgumentException If sz is <= 0
 
     public BufferedWriter(Writer outint sz) {
        super(out);
        if (sz <= 0)
            throw new IllegalArgumentException("Buffer size <= 0");
        this. = out;
         = new char[sz];
         = sz;
         = 0;
         = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("line.separator"));
    }

    
Checks to make sure that the stream has not been closed
    private void ensureOpen() throws IOException {
        if ( == null)
            throw new IOException("Stream closed");
    }

    
Flushes the output buffer to the underlying character stream, without flushing the stream itself. This method is non-private only so that it may be invoked by PrintStream.
    void flushBuffer() throws IOException {
        synchronized () {
            ensureOpen();
            if ( == 0)
                return;
            .write(, 0, );
             = 0;
        }
    }

    
Writes a single character.

Throws:
IOException If an I/O error occurs
    public void write(int cthrows IOException {
        synchronized () {
            ensureOpen();
            if ( >= )
                flushBuffer();
            [++] = (charc;
        }
    }

    
Our own little min method, to avoid loading java.lang.Math if we've run out of file descriptors and we're trying to print a stack trace.
    private int min(int aint b) {
        if (a < breturn a;
        return b;
    }

    
Writes a portion of an array of characters.

Ordinarily this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed. If the requested length is at least as large as the buffer, however, then this method will flush the buffer and write the characters directly to the underlying stream. Thus redundant BufferedWriters will not copy data unnecessarily.

Parameters:
cbuf A character array
off Offset from which to start reading characters
len Number of characters to write
Throws:
IOException If an I/O error occurs
    public void write(char cbuf[], int offint lenthrows IOException {
        synchronized () {
            ensureOpen();
            if ((off < 0) || (off > cbuf.length) || (len < 0) ||
                ((off + len) > cbuf.length) || ((off + len) < 0)) {
                throw new IndexOutOfBoundsException();
            } else if (len == 0) {
                return;
            }
            if (len >= ) {
                /* If the request length exceeds the size of the output buffer,
                   flush the buffer and then write the data directly.  In this
                   way buffered streams will cascade harmlessly. */
                flushBuffer();
                .write(cbufofflen);
                return;
            }
            int b = offt = off + len;
            while (b < t) {
                int d = min( - t - b);
                System.arraycopy(cbufbd);
                b += d;
                 += d;
                if ( >= )
                    flushBuffer();
            }
        }
    }

    
Writes a portion of a String.

If the value of the len parameter is negative then no characters are written. This is contrary to the specification of this method in the superclass, which requires that an java.lang.IndexOutOfBoundsException be thrown.

Parameters:
s String to be written
off Offset from which to start reading characters
len Number of characters to be written
Throws:
IOException If an I/O error occurs
    public void write(String sint offint lenthrows IOException {
        synchronized () {
            ensureOpen();
            int b = offt = off + len;
            while (b < t) {
                int d = min( - t - b);
                s.getChars(bb + d);
                b += d;
                 += d;
                if ( >= )
                    flushBuffer();
            }
        }
    }

    
Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.

Throws:
IOException If an I/O error occurs
    public void newLine() throws IOException {
        write();
    }

    
Flushes the stream.

Throws:
IOException If an I/O error occurs
    public void flush() throws IOException {
        synchronized () {
            flushBuffer();
            .flush();
        }
    }
    public void close() throws IOException {
        synchronized () {
            if ( == null) {
                return;
            }
            try {
                flushBuffer();
            } finally {
                .close();
                 = null;
                 = null;
            }
        }
    }
New to GrepCode? Check out our FAQ X