Writing files in Java

I am going to show example which shows how to write a file in Java.
If you want to write some file you should start with FileOutputStream. This class is a concrete subclass of OutputStream.
Example:

package tutorial;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class Main{ public static void main(String[] args){ FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try{ String workingDirectory = System.getProperty("user.dir"); File fileDir = new File(workingDirectory,"src/tutorial"); File readFile = new File(fileDir,"Main.java"); File writeFile = new File(fileDir,"CopyFile"); fileInputStream = new FileInputStream(readFile);//  fileOutputStream = new FileOutputStream(writeFile,true); fileOutputStream = new FileOutputStream(writeFile); show(fileInputStream,fileOutputStream); } catch (IOException ex){ ex.printStackTrace(); } finally{ try{if (fileInputStream != null){fileInputStream.close();}  } catch (IOException ex){}  try{if (fileOutputStream != null){fileOutputStream.close();}  } catch (IOException ex){}  }  }  private static void show(FileInputStream fileInputStream,FileOutputStream fileOutputStream) throws IOException{ byte[] buffer = new byte[1024]; while (true){ int bytesRead = fileInputStream.read(buffer); if (bytesRead == -1){break; }  fileOutputStream.write(buffer,0,bytesRead); }  }}

I had commented code in line number 26.
This constructor lets you specify whether the file’s contents should be erased before data is written into it (append == false) or whether data is to be tacked onto the end of the file (append == true). You can uncomment this line and comment next line of code and you will see how content is added in the end of the file.

Share

No related posts.

Leave a Reply

  

  

  

You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna,tincidunt vitae molestie nec,molestie at mi. Nulla nulla lorem,suscipit in posuere in,interdum non magna.