tags:

views:

105

answers:

3

How can I read the file information (for example size, line count, last modification, etc) from a file in the file-system or the directory content with JAVA? I need it for a linux operating system.

Thanks

Ps. This is my first question, althought I have user this forum for a while so please be kind :P

+1  A: 

Try looking in to the File api. There are a bunch of methods like 'lastModified', 'length', and most of what you should need.

rmarimon
+1  A: 

Use File class (except for line count - see this Q/A for that)

java.io.File.length()

lastModified()

Also, if you can get your Java program to make a system call, you can use Unix's wc -l command to count the lines for you - might be faster than Java but costs you a spawned-off process

DVK
thanks a lot, but any idea for line count?? I really don't want to read the whole file :S. It is not an option, this are REALLY large files.
Pizza
See the link in my first line for line count. Also, you can LineNumberReader - see http://www.roseindia.net/java/example/java/io/NumberOfLine.shtml
DVK
And no, you can't really count the lines in a file without actually reading the file, unless the file format explicitly stores line count as a number in the beginning or end of the file (some file formats do).
DVK
Take a look at the link DVK provided before dismissing the idea of reading in the whole file. It's probably faster than you think, and there's no way around it to get the number of lines.
gregcase
Thanks, it helps me a lot, I will try counting lines. If it is very slow, I will try the system call. It is not pretty but no other option.
Pizza
+1  A: 

For what it is worth, "line count" is not a file attribute in UNIX or Linux.

If you want a line count (assuming that it is a valid concept) you need to figure it out by reading the file. Simply counting newline characters gives a roughly correct answer for "text" files, but it may give a bogus answer in other cases. A complete answer involves:

  • determining the file's type,
  • deciding whether "line count" makes sense for the file type,
  • deciding whether to count the lines or retrieve a line count from the file's internal metadata, and
  • (if necessary) counting the lines in a way that is appropriate to the file type.
Stephen C
the file is a log file from apache, so it is plain text. The only solution is to count lines. I will try counting with java.
Pizza