Java I/O How to - Save string value to a file








Question

We would like to know how to save string value to a file.

Answer

//  www .  j  av a2  s.c om


   

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Main {
  public static void main(String[] argv) {
    saveFile("c:\\a.txt", "value");
  }

  public static void saveFile(final String fileName, final String str) {
    try {
      File f = new File(fileName);
      if (new File(f.getParent()).exists() == false) {
        f.getParentFile().mkdirs();
      }
      f.createNewFile();
      PrintStream p = new PrintStream(new FileOutputStream(f, false));
      p.println(str);
      p.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.err.println(fileName);
    }
  }
}