View Category

Read the contents of a file into a string

python
contents = open('myFile.txt', 'rt').read()
ruby
file = File.new("Solution108.rb")
whole_file = file.read
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);
}
php
$file_contents = file_get_contents("file.txt");

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())
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{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);
}
php
$lines = file('file.txt');
foreach ($lines as $lnum => $line) {
echo $line_num."> ".$line; // you may want to add a <br />\n
}
<?php
$lines = new SplFileObject('file.txt');
foreach ($lines as $line) {
echo $line;
}
?>

Write a string to a file

python
open('test.txt', 'wt').write('Hello World!')
ruby
File.new("a_file", "w") << "some text"
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!");
}
php
/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionnames. Please remove it :)
****/

if ($fh = f open("file.txt", 'w')) {
f write($fh, "Some text\n");
f close($fh);
}
<?php
file_put_contents('file.txt', 'a string');
?>

Append to a file

python
open('test.txt', 'at').write('Hello World!\n')
ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()
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!");
}
php
<?php
if ($fh = fopen("file.txt", 'a')) { // a == append
fwrite($fh, "Append some text\n");
fclose($fh);
}
?>
<?php
file_put_contents('file.txt', 'a string to append', FILE_APPEND);
?>

Process each file in a directory

python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}
java
for (File file : (new File("c:\\")).listFiles()) process(file);
php
if ($dh = opendir($dir)) { // if we have access
while (($file = readdir($dh)) !== false) { // as long as there is a file
echo "name: $file\n"; // echo its name
}
closedir($dh); // close the dir
}

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)
ruby
def procdir(dirname)
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
puts "DIRECTORY: #{dirpath}" ; procdir(dirpath)
end
else
puts "FILE: #{dirpath}"
end
end
end

# ------

procdir('/tmp')
java
processDirectory(new File("c:\\"));
php

if ($dir_handle = opendir($dir))
list_dir($dir_handle);

function list_dir($dh) {
// as long as we can read the dir
while (($file = readdir($dh)) !== false) {
// if it's a dir and it's not the current dir nor the above dir
if (is_dir($file) && $file != '.' && $file !='..') {
// open the dir, print it's name and all files inside
$handle = opendir($file);
echo $file."\n";
list_dir($handle);
// if it's a simple file
} else if ($file != '.' && $file !='..') {
// type it's name
echo $file."\n";
}
}
closedir($dir_handle); // close the dirs
}