Take the 2-minute tour ×

I have problem while writing to the file. I want to write contents of my input file to output file but while writing to the file, I am getting NULL value written at the end of file.

What's the reason behind that?

My code is:

 import java.io.BufferedReader;
 import java.io.DataInputStream;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class FileReading {

 * @param args
 * @throws IOException 
    // TODO Auto-generated method stub

    FileInputStream fi=new  
    DataInputStream di=new DataInputStream(fi);

    BufferedReader buf=new BufferedReader(new InputStreamReader(di));
    FileOutputStream fout=new FileOutputStream("E:\\Tejas\\NewData_FromNov\\New_Folder\\Out_bb.txt");
    int ss;

    byte[] input=new byte[500];
    int len=input.length;




share|improve this question
Do you mean the byte 0x00, or the string "NULL"? –  Mark Byers Nov 27 '11 at 9:12

2 Answers 2

up vote 3 down vote accepted

You're always writing out the full buffer, even if you've only read part of it, because the third argument to write is len (the length of the buffer) instead of ss (the number of bytes read). Your loop should look like this:

int bytesRead; // Easier to understand than "ss"
byte[] buffer = new byte[500];

while((ss = di.read(buffer, 0, buffer.length)) != -1)
    fout.write(buffer, 0, bytesRead);


  • You should close both the input and output streams in finally blocks to ensure they're always closed (even if there's an exception)
  • You don't need a DataInputStream - just a FileInputStream is fine here
  • You're not using your BufferedReader at all
  • Consider using Guava or a similar third-party library which contains utility methods to do all of this
share|improve this answer
A sage reminder to check file size of input against output files. –  Andrew Thompson Nov 27 '11 at 9:18

The read method returns the number of actually read bytes, or -1 if the end of the stream has been reached. So you should only write ss bytes, and not len bytes:

while ((ss = di.read(input, 0, len)) != -1) {
    fout.write(input, 0, ss);

Note thet the DataInputStream and the BufferedReader are completely unnecessary here.

share|improve this answer

Your Answer


