Monday, 11 July 2016

Writing file in Java

Though Java provides classes like FileOutPutStream and FileWriter to write files using byte stream and character stream respectively but using them directly will slow down the I/O operation considerably.

It is always advisable to use BufferedOutputStream or BufferedWriter because that will provide buffering to the output streams and won't cause a call to the underlying system for each byte written. Buffered output streams write data to a buffer, and the native output API is called only when the buffer is full, making I/O operation more efficient.

It is same as reading file using BufferedReader where again the advantage of using buffered I/O streams is that; in case of Buffered input streams data is read from a memory area known as a buffer.

Writing file using BufferedOutputStream

BufferedOutputStream is a wrapper class over the OutputStream class and it adds buffering capability to the output stream.

Here one thing to note is – If your file contains character data, the best approach is to use character streams like BufferedWriter. Byte streams should only be used for the most primitive I/O.

The write method of the BufferedOuputStream takes either a byte array or an int as an argument thus you have to call getBytes() on any String that is passed to the write method.

Java code

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWriteDemo {

 public static void main(String[] args) {
  writeFileContent("G:\\test.txt");
 }
 
 /**
  * 
  * @param fileName
  */
 private static void writeFileContent(String fileName){
  BufferedOutputStream bs = null;
  try {
   bs = new BufferedOutputStream(new FileOutputStream(fileName));
   bs.write("Writing one line".getBytes());
   // For windows, only \n for linux
   bs.write("\r\n".getBytes());
   bs.write("Writing second line".getBytes());
   
  } catch (IOException ioExp) {
   // TODO Auto-generated catch block
   ioExp.printStackTrace();
  }finally{
   if(bs != null){
    try {
     bs.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }

}

Writing file using BufferedWriter

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.

Constructors

  • BufferedWriter(Writer out) - Creates a buffered character-output stream that uses a default-sized output buffer.
  • BufferedWriter(Writer out, int sz) - Creates a new buffered character-output stream that uses an output buffer of the given size.

Java code

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWrite {

 public static void main(String[] args) {
  writeFileContent("G:\\test1.txt");

 }
 
 /**
  * 
  * @param fileName
  */
 private static void writeFileContent(String fileName){
  //BufferedWriter bw = null;
  // Using try-with-resources here 
  try(BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
   //bw = new BufferedWriter(new FileWriter(fileName));
   bw.write("Writing one line");
   bw.newLine();
   bw.write("Writing second line");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

Note that in this program try-with-resources is used to automatically manage resources. It is available from Java 7 and above.

Writing using Files class methods

In Java 7 Files class is added which provides write() method to write to a file. There is also a newBufferedWriter method with 2 arguments, added in Java 8 that can be used to write to a file.

Using write() method

There are 2 overloaded versions of write method

  • public static Path write(Path path, byte[] bytes,OpenOption... options) throws IOException – Write bytes to a file specified by the path. Options varargs specifies whether new file is created for writing or bytes are appended to an already existing file. If no options are present then this method works as if the  CREATE, TRUNCATE_EXISTING, and WRITE options are present.
  • public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException - Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system propertyline.separator. Characters are encoded into bytes using the specified charset.

Example code

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileWrite8 {
 public static void main(String[] args) {
  String content = "This is the line to be added.\nThis is another line.";
  try {
   Files.write(Paths.get("G://test.txt"), content.getBytes());
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
 
}

Here note that String is converted to Byte array and also there is no option parameter which means creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

Using newBufferedWriter method

There are 2 overloaded versions of newBufferedWriter method
  • public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. If no options are present then this method works as if the CREATE,  TRUNCATE_EXISTING, and WRITE options are present.
  • public static BufferedWriter newBufferedWriter(Path path, Charset cs,OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. Here path is the path to the file, cs is the charset to use for encoding and options parameter specifies how the file is opened.

Example Code

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileWrite8 {
 public static void main(String[] args) {
  Path path = Paths.get("G://test.txt");
  try (BufferedWriter writer = Files.newBufferedWriter(path)) {
      writer.write("Hello World");
      writer.newLine();
      writer.write("Hello again");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Here note that no option parameter is given which means creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

That's all for this topic Writing file in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading delimited file in Java using Scanner
  2. How to read file from the last line in Java
  3. How to find last modified date of a file in Java
  4. Reading file in Java 8
  5. Zipping files in Java
  6. try-with-resources in Java 7

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment