View Category

Read the contents of a file into a string

scala
val text = FileUtils.readFileToString(new File("Solution467.scala"))
val text = Source.fromFile("Solution1256.scala").mkString("")
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);
}

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
scala
val source = Source.fromFile(new File("Solution468.scala")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
val source = Source.fromFile(new File("Solution469.scala")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), 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);
}

Write a string to a file

scala
FileUtils.writeStringToFile(new File("test.txt"), "This line overwites file contents!")
val fw = new FileWriter("test.txt") ; fw.write("This line overwites file contents!") ; fw.close()
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!");
}

Append to a file

scala
val fw = new FileWriter("test.txt", true) ; fw.write("This line appended to file!") ; fw.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!");
}

Process each file in a directory

scala
for (file <- new File("c:\\").listFiles) { processFile(file) }
java
for (File file : (new File("c:\\")).listFiles()) process(file);

Process each file in a directory recursively

scala
processDirectory(new File("c:\\"))
java
processDirectory(new File("c:\\"));