1

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 presently working on linux operating system. Kindly give some ideas particularly for Linux OS.

Thanks in Advance.

Sayakiss
  • 6,878
  • 8
  • 61
  • 107
Pizza
  • 260
  • 2
  • 8

3 Answers3

2

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.

The other attributes you listed (file size and modification time) can be accessed in Java using the classic java.io.File API, or the new Java 7 java.nio.file.Files API.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 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 May 29 '10 at 20:31
1

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

Ricardo Marimon
  • 10,339
  • 9
  • 52
  • 59
1

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

Community
  • 1
  • 1
DVK
  • 126,886
  • 32
  • 213
  • 327
  • 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 May 29 '10 at 02:52
  • 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 May 29 '10 at 02:58
  • 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 May 29 '10 at 02:59
  • 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. – Greg Case May 29 '10 at 03:00
  • 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 May 29 '10 at 20:30