FileOutputStream Write String into File in Java | Java @ Desk
Home » » FileOutputStream Write String into File in Java

FileOutputStream Write String into File in Java

FileOutputStream Write String into File in Java

java.io.FileOutputStream class is used to write string into a file in java. If the file does not exists at the path provided, FileOutputStream class first creates the new file.

With FileOutputStream, no need to check if File exists and no need to create the file.

The constructor takes the java.io.File object and creates the new file.

Its very important to call the close() method on the FileOutputStream otherwise contents will not be written to the file created.

The difference between FileWriter to write into File and FileOutputStream is FileWriter write() method takes String content whereas FileOutputStream write() method takes bytes to write the content to file.

To convert String to bytes, use getBytes() method of String class

This implementation will over write the content in the file. If you want to append the content to end of existing file click FileOutputStream Append String to End of Existing File in Java

Client code

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamWrite {
 public static void main(String args[]) throws IOException {
  FileOutputStream fileOutputStream = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileOutputStream = new FileOutputStream(file);
   fileOutputStream.write("Write these bytes to file".getBytes());
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   fileOutputStream.flush();
   fileOutputStream.close();
  }
 }
}




5 comments:

  1. Thank You. Its is really worth reading this blog. This link will help beginners to get started: http://www.javatrainingchennai.in/

    ReplyDelete
  2. and if I want to write to a different IP address. comments

    ReplyDelete
  3. and if I want to write to a different IP address. comments

    ReplyDelete
  4. and if I want to write to a different IP address. comments

    ReplyDelete