Reading in a file with Perl and Java
This is why people love Perl. A small amount of work to do a BIG TASK:
$file_name = "somefile.txt";
open (my $fh, $file_name) or die "Ouch: $!\n";
# $text variable now contains whatever the file contains
$text = do {
local $/ = undef;
<$fh>;
};
close($fh) or die("Ugh: $!\n");
Just to compare, this is how you would do in Java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ReadFile {
public static void main (String[] args) {
try {
String filename = "somefile.txt";
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
ArrayList lines = new ArrayList();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
}
catch (IOException e) {
System.err.println("OUCH!!!!");
}
}
}
After this, you get a list of string that contains contents of a file. This is a little extreme case, but still… it shows how much of work you would do if you want to do the same job in Java.
