Difference between revisions of "Save a string to a file"

From CodeCodex

(OCaml: added a solution using Micmatch)
(Java)
Line 1: Line 1:
 
==Implementations==
 
==Implementations==
 
===Java===
 
===Java===
 +
If java.io.* is imported:
 
<pre>
 
<pre>
 
public static void saveTextFile(String contents, File file) throws IOException {
 
public static void saveTextFile(String contents, File file) throws IOException {
Line 7: Line 8:
 
  out.close();
 
  out.close();
 
}
 
}
 +
</pre>
 +
Otherwise use this:
 +
<pre>
 +
  public static void saveTextFile(String contents, java.io.File file) throws java.io.IOException {
 +
  java.io.PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(file));
 +
  out.print(contents);
 +
  out.close();
 +
  }
 
</pre>
 
</pre>
  

Revision as of 18:26, 28 July 2006

Implementations

Java

If java.io.* is imported:

public static void saveTextFile(String contents, File file) throws IOException {
 PrintWriter out = new PrintWriter(new FileWriter(file));
 out.print(contents);
 out.close();
}

Otherwise use this:

  public static void saveTextFile(String contents, java.io.File file) throws java.io.IOException {
	  java.io.PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(file));
	  out.print(contents);
	  out.close();
  }

OCaml

# let save file string =
    let channel = open_out file in
    output_string channel string;
    close_out channel;;
val save : string -> string -> unit = <fun>

For example:

# save "foo" "bar\n";;
- : unit = ()
$ cat foo
bar

The Micmatch library provides a function which does this directly (Micmatch.Text.save):

# open Micmatch;;
# Text.save "foo" "bar\n";;
- : unit = ()