Read File/Directory properties with java
How can I read the file information (for examp开发者_开发技巧le 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.
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.
Try looking in to the File api. There are a bunch of methods like 'lastModified', 'length', and most of what you should need.
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
精彩评论