Open and read a file
I've not verified any of this code works.
RandomAccessFile f=new RandomAccessFile("test.txt", "r");
f.readFully(new byte[(int)f.length()]);
f.close();
or with a try finally block,
RandomAccessFile f = new RandomAccessFile("test.txt", "r");
try {
f.readFully(new byte[(int) f.length()]);
}
finally {
f.close();
}
or possibly this example,
FileUtils.readBytes(new File("test.txt"));
A nice PHP comparison
In PHP it can be done in one line of code:
As it can be done in Java:
Now, for more serious code that'd actually handle a couple of problems, you'd have to write it like this (PHP):
$content = file_get_contents("file.txt");
} else {
// do something else
}
Upps... that doesn't look quite as nice, doesn't it? Let's see the Java-Version:
String content = FileUtils.read("file.txt");
} catch(IOException e) {
// do something else
}
Ok. Both have 5 lines of code, but which one looks better? I think the Java-Version is cleaner. Know what? Let's do it in PHP (version 5) again:
$content = FileUtils::read("file.txt");
} catch($exception) {
// do something else
}
References
[Click to add or edit comments])
Please prepend comments below including a date