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:

$content = file_get_contents("file.txt");

As it can be done in Java:

String content = FileUtils.read("file.txt");

Now, for more serious code that'd actually handle a couple of problems, you'd have to write it like this (PHP):

if(file_exists("file.txt") || !is_readable("file.txt")) {
    $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:

try {
    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:

try {
    $content = FileUtils::read("file.txt");
} catch($exception) {
    // do something else
}

References

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.