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
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream fi=new
FileInputStream("E:\\Tejas\\NewData_FromNov\\New_Folder\\bb.txt");
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;
while((ss=di.read(input,0,len))!=-1)
{
System.out.println(ss);
//fout.write(ss);
fout.write(input,0,len);
}
fout.close();
}
}
You’re always writing out the full buffer, even if you’ve only read part of it because the third argument to
writeislen(the length of the buffer) instead ofss(the number of bytes read). Your loop should look like this:Additionally:
finallyblocks to ensure they’re always closed (even if there’s an exception).DataInputStream– just aFileInputStreamis fine here.BufferedReaderat all.