I have a java program in a certain directory. I would like to make it find a list of all files that end with .dat
or .DAT
in the same directory as the program. Then I need to look at the first couple of lines of each file and parse a title string. The program should return an array of the file names, and an array of the first three lines of each file. I am pretty new to IO stuff, can anyone help?
Example: C:/my_directory/
Files: Program.class,
FOO.DAT (starts with "Lorem\nipsem\n$$0")开发者_运维技巧,
bar.dat (starts with "ipsem\nLorem\n$$0")
Return: ["FOO.DAT","bar.dat"] and ["Lorem\nipsem\n","ipsem\nLorem\n"]
Thanks in advanced!
The following code snippet prints out all the files that have .dat
or .DAT
file extensions in a given directory. Try to figure out how you can read first three lines from a file. That must be fairly straightforward
File tmp = new File( "/tmp");
List<String> fileList = new ArrayList<String>();
if( tmp.isDirectory())
{
for( File f : tmp.listFiles())
{
if( f.isFile() )
{
if((f.getName().endsWith( ".dat") || f.getName().endsWith(".DAT")))
{
fileList.add( f.getName() );
}
}
}
for( String fileName : fileList)
{
System.out.println( fileName);
}
}
精彩评论