Difference between revisions of "Reading text from a file"

From CodeCodex

(OCaml)
Line 14: Line 14:
  
 
===OCaml===
 
===OCaml===
We're careful to close the file and reraise any exception generated by the given <tt>process</tt> function:
 
 
<pre>
 
<pre>
 
# let process_file process filename =
 
# let process_file process filename =
 
     let ch = open_in filename in
 
     let ch = open_in filename in
 
     try while true do process(input_line ch) done
 
     try while true do process(input_line ch) done
     with
+
     with _ -> close_in ch;;
      End_of_file -> close_in ch
+
      exn -> close_in ch; raise exn;;
+
 
val process_file : (string -> 'a) -> string -> unit = <fun>
 
val process_file : (string -> 'a) -> string -> unit = <fun>
 
</pre>
 
</pre>
Line 27: Line 24:
 
[[Category:Java]]
 
[[Category:Java]]
 
[[Category:I/O]]
 
[[Category:I/O]]
 +
[[Category:Objective Caml]]

Revision as of 19:37, 31 July 2006

Implementations

Java

    try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;
        while ((str = in.readLine()) != null) {
            process(str);
        }
        in.close();
    } catch (IOException e) {
    }

OCaml

# let process_file process filename =
    let ch = open_in filename in
    try while true do process(input_line ch) done
    with _ -> close_in ch;;
val process_file : (string -> 'a) -> string -> unit = <fun>