2 ways to write String to file using FileOutputStream and apache commons in java file IO




Difference between FileInputStream and BufferedInputStream in java file IO

Read text from file using FileInputStream in java file IO




Program 1 to Write String to file using Apache commons >

Its probably the easiest way to write String in file.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/** JavaMadeSoEasy.com */
public class WriteStringToFileUsingApacheCommons {
   public static void main(String... args) {
          try {
                 String str = "You are learning File IO from javaMadeSoEasy.com";
                 FileUtils.writeStringToFile(new File("test.txt"), str);
                 System.out.println("String str has been written successfully in file "
                                            + "using org.apache.commons.io.FileUtils");
          } catch (IOException e) {
                 e.printStackTrace();
          }
   }
}
/* OUTPUT
String str has been written successfully in file using org.apache.commons.io.FileUtils
*/


Program 2 to Write String to file using FileOutputStream in java file IO >


import java.io.FileOutputStream;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class WriteStringToFileUsingFileOutputStream {
   public static void main(String... args) {
          FileOutputStream fos = null;
          try {
                 // if file doesn't exist new file will be created
                 // if file already exists contends will be overridden.
                 fos = new FileOutputStream("c:/myFile.txt");
                 String str="You are learning File IO from javaMadeSoEasy.com";
                 fos.write(str.getBytes()); //convert String into byte array to write in file
                
                 fos.flush(); //bytes in buffer are written in file
                
                 System.out.println("String str has been written successfully in file "
                              + "using FileOutputStream");
                
          } catch (IOException e) {
                 e.printStackTrace();
          } finally {
                 try {
                       if (fos != null){
                              fos.close(); //close FileOutputStream
                       }
                 } catch (IOException e) {
                       e.printStackTrace();
                 }
          }
   }
}
/* OUTPUT
String str has been written successfully in file using FileOutputStream
*/


Or simply you may Write String to file using BufferedWriter and FileWriter in java file IO, probably the best way to write String in file.


RELATED LINKS>


Write String to file using BufferedOutputStream (and FileOutputStream) in java file IO

Program to Write in file using PrintWriter to in java



Program to Encrypt and decrypt text using password - Write encrypted text to file | Read encrypted text from file in java


No comments:

Post a Comment