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);
}
try
{
raf = new RandomAccessFile("Solution399.java", "r");
buffer = new byte[(int)raf.length()]; raf.read(buffer);
text = new String(buffer);
}
clojure
(slurp "/tmp/foobar")
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
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())
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);
}
// 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
}
}
}
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);
}
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);
}
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
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!");
}
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!");
}
try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt")));
pw.print("This line overwites file contents!");
}
clojure
(with-out-writer "output.txt" (println "Hello file!"))
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!");
}
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!");
}
try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
pw.print("This line appended to file!");
}
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
Process each file in a directory
python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
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);
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
(map process-file (.listFiles (File. ".")))
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)
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
java
processDirectory(new File("c:\\"));
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
(map process-file (file-seq (File. ".")))
