Java I/O – How to write to a file using FileOutputStream




Java Tutorial for Beginners
Java Tutorial for Beginners

In the previous examples How to create a file in Java. Now in this example we will see how to write to a file in Java using FileOutputStream class.

  • A FileOutputStream writes to a file on disk
  • FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

So Lets see the example below.

/**
 * Created by codebind.com.
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Sample {
    public static void main(String[] args) {
        //declare the file path here
        File file = new File("C:/myfile.txt");
        FileOutputStream fos = null;
        String content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
        try {

            fos = new FileOutputStream(file);
          /* Tests whether the file or directory denoted by this abstract pathname exists.*/
            if (!file.exists()) {
                file.createNewFile();
            }

	  /* convert String content into bytes
	   */
            byte[] bytesArray = content.getBytes();

            fos.write(bytesArray);
            fos.flush();
            System.out.println("content written to the file Successfully");
        }
        catch (IOException ioex) {
            ioex.printStackTrace();
        }
        finally {
            try {
                if (fos != null)
                {
                    fos.close();
                }
            }
            catch (IOException ioe) {
                System.out.println("Error in closing the file Stream");
            }
        }
    }
}

Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*