View Category

Read the contents of a file into a string

python
contents = open('myFile.txt', 'rt').read()
clojure
(slurp "/tmp/foobar")
fsharp
let file = new FileStream("test.txt", FileMode.Open)
let buffer = new String((new BinaryReader(file)).ReadChars(Convert.ToInt32(file.Length)))
let stream = new StreamReader("test.txt")
let buffer = stream.ReadToEnd()
let buffer = File.ReadAllText("test.txt")
fantom
contents := File(`file.text`).readAllStr
java
String text = FileUtils.readFileToString(new File("Solution109.java"), "UTF-8");
RandomAccessFile raf = null; byte[] buffer; String text = null;

try
{
raf = new RandomAccessFile("Solution399.java", "r");
buffer = new byte[(int)raf.length()]; raf.read(buffer);
text = new String(buffer);
}
cpp
IO::FileStream^ file; String^ buffer;

try
{
file = gcnew IO::FileStream("test.txt", IO::FileMode::Open);
buffer = gcnew String((gcnew IO::BinaryReader(file))->ReadChars(file->Length));
}
IO::StreamReader^ stream; String^ buffer;

try
{
stream = gcnew IO::StreamReader("test.txt");
buffer = stream->ReadToEnd();
}
String^ buffer = IO::File::ReadAllText("test.txt");
groovy
contents = file.text

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
fsharp
let stream = new StreamReader("test.txt")
let mutable i = 1
let mutable line = stream.ReadLine()
while (line <> null) do printfn "%d> %s" i line ; line <- stream.ReadLine() ; i <- i + 1 done
stream.Close()
let proc_a_line (filename : string) proc =
let stream = new StreamReader(filename)
let rec proc_a_line' count line =
match line with
| null -> stream.Close()
| _ -> proc count line ; proc_a_line' (count + 1) (stream.ReadLine())
proc_a_line' 1 (stream.ReadLine())

// ------

let _ = proc_a_line "test.txt" (fun i line -> printfn "%d> %s" i line)
let reader(filename : string) = seq {
use sr = new StreamReader(filename)
while not sr.EndOfStream do
let line = sr.ReadLine()
yield line
done
}

// ------

reader("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
File.ReadAllLines("test.txt") |> Array.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
// Unlike ReadAllLines, ReadLines (new in .NET 4) only reads the file
// one line at a time, rather than reading the entire file into an array first.

open System.IO
File.ReadLines("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }
java
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Solution104.java"));
String line = null;
int lineNumber = 1;
while ((line=br.readLine())!=null) {
System.out.println(lineNumber + "> " + line);
lineNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br!=null) {
try {
br.close();
} catch (Exception e) {
// ok
}
}
}
LineNumberReader lnr = null; PrintWriter pw = null; String line;

try
{
lnr = new LineNumberReader(new FileReader("Solution400.java"));
pw = new PrintWriter(System.out);
while ((line = lnr.readLine()) != null) pw.printf("%d> %s\n", lnr.getLineNumber(), line);
}
cpp
IO::StreamReader^ stream; String^ ln; int i = 0;

try
{
stream = gcnew IO::StreamReader("test.txt");
while ((ln = stream->ReadLine())) Console::WriteLine("{0}> {1}", ++i, ln);
}
int i = 0;
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);
groovy
int count = 0
file.eachLine { line ->
println "${++count} > $line"
}
file.eachLine { line, count ->
println "${++count} > $line"
}

Write a string to a file

python
open('test.txt', 'wt').write('Hello World!')
clojure
(with-out-writer "output.txt" (println "Hello file!"))
fsharp
let stream = new StreamWriter("test.txt", false)
stream.WriteLine("This line overwrites file contents!")
fantom
File(`out.txt`).out.writeChars("some text").flush
java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt");
fw.write("This line overwites file contents!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt")));
pw.print("This line overwites file contents!");
}
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}
groovy
file.delete()
file << 'some text'
file.text = 'some text'

Append to a file

python
open('test.txt', 'at').write('Hello World!\n')
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
fsharp
let stream = new StreamWriter("test.txt", true)
stream.WriteLine("This line appended to file!")
fantom
File(`out.txt`).out(true).writeChars("some text").flush
java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt", true);
fw.write("This line appended to file!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
pw.print("This line appended to file!");
}
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}
groovy
file << 'some text'

Process each file in a directory

python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
fsharp
let dirname = "c:\\"

let processFile filename = printfn "%s" filename
for filename in Directory.GetFiles(dirname) do processFile filename done
let dirname = "c:\\"

Directory.GetFiles(dirname) |> Array.iter (fun filename -> printfn "%s" filename)
fantom
File(`./`).list.each { process(it) }
java
for (File file : (new File("c:\\")).listFiles()) process(file);
cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);
groovy
dir.eachFile{ f -> process(f) }

Process each file in a directory recursively

python
import os
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
fsharp
let processDirectory dirname proc =
let rec processDirectory' dirname' =
Directory.GetFiles(dirname') |> Array.iter proc
Directory.GetDirectories(dirname') |> Array.iter processDirectory'
processDirectory' dirname

// ------

let dirname = "c:\\"

processDirectory dirname (fun filename -> printfn "%s" filename)
fantom
File(`./`).walk { process(it) }
java
processDirectory(new File("c:\\"));
cpp
void processFile(String^ filename) { Console::WriteLine("{0}", filename); }

void processDirectory(String^ dirname)
{
for each(String^ filename in IO::Directory::GetFiles(dirname)) processFile(filename);
for each(String^ subdirname in IO::Directory::GetDirectories(dirname)) processDirectory(subdirname);
}

int main()
{
processDirectory("c:\\");
}
groovy
dir.eachFileRecurse{ f -> process(f) }