View Category

Read the contents of a file into a string

python
contents = open('myFile.txt', 'rt').read()
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
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);
}
fantom
contents := File(`file.text`).readAllStr

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())
csharp
int counter = 0;

// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
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);
}
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }

Write a string to a file

python
open('test.txt', 'wt').write('Hello World!')
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
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!");
}
fantom
File(`out.txt`).out.writeChars("some text").flush

Append to a file

python
open('test.txt', 'at').write('Hello World!\n')
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
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!");
}
fantom
File(`out.txt`).out(true).writeChars("some text").flush

Process each file in a directory

python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
java
for (File file : (new File("c:\\")).listFiles()) process(file);
fantom
File(`./`).list.each { process(it) }

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)
java
processDirectory(new File("c:\\"));
fantom
File(`./`).walk { process(it) }