Pizza
Pizza

Reputation: 260

Read File/Directory properties with java

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.

Upvotes: 1

Views: 1676

Answers (3)

Stephen C
Stephen C

Reputation: 719446

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.

Upvotes: 2

DVK
DVK

Reputation: 129529

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

Upvotes: 1

Ricardo Marimon
Ricardo Marimon

Reputation: 10697

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

Upvotes: 1

Related Questions