September 04, 2010, 02:00:06 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  Home Help Media Affiliates Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Listing files with Java's File class  (Read 891 times)
0 Members and 1 Guest are viewing this topic.
jurka
Moderator
Member
*
*

Reputation: 5
Offline Offline
Posts: 188
Referrals: 0

Awards
« on: February 28, 2009, 11:16:40 AM »

Code
GeSHi (java):
  1. package Tutorial
  2.  
  3. object ControlStructures {
  4.  def main(args : Array[String]) : Unit = {
  5.    val location = "c:\\"
  6.    val fileType = ".ini"
  7.    val files = (new java.io.File(location)).listFiles
  8.  
  9.    // We can add in for expression if statements, filtering
  10.    for (file <- files if file.getName.endsWith(fileType)) {
  11.      println(file.getName)
  12.    }
  13.  
  14.  }
  15. }
  16.  
Created by GeSHI 1.0.7.20

with more filtering..
Code
GeSHi (java):
  1. object ControlStructures {
  2.  def main(args : Array[String]) : Unit = {
  3.    val location = "c:\\"
  4.    val files = (new java.io.File(location)).listFiles
  5.  
  6.    // We can add in for expression if statements, filtering
  7.    for (
  8.      file <- files
  9.      if file.isFile; // need to add semicolons because it's meant as a one line
  10.      if file.canRead;
  11.      if file.getName.endsWith(".sqm")
  12.    ) println(file.getName)
  13.  
  14.  }
  15. }
  16.  
  17.  
Created by GeSHI 1.0.7.20

Searching in files, also this example uses nested looping
Code
GeSHi (java):
  1.  
  2. object ControlStructures {
  3.  def main(args : Array[String]) : Unit = {
  4.    val location = "c:\\"
  5.    val fileType = ".txt"
  6.    val files = (new java.io.File(location)).listFiles
  7.  
  8.    def fileLines(file: java.io.File) =
  9.      scala.io.Source.fromFile(file).getLines.toList
  10.  
  11.    def grep(pattern: String) =
  12.      for (
  13.        file <- files
  14.        if file.getName.endsWith(fileType);
  15.        line <- fileLines(file)
  16.        if line.trim.matches(pattern)
  17.      ) println(file.getName + "=> " + line.trim)
  18.  
  19.    grep(".*Java.*")
  20.  }
  21. }
  22.  
  23.  
Created by GeSHI 1.0.7.20
Logged
Javaforums.net :: a community about Java software development.
« on: February 28, 2009, 11:16:40 AM »

Your Ad Here
 Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.10 | SMF © 2006-2009, Simple Machines LLC
TinyPortal v0.9.8 © Bloc
Valid XHTML 1.0! Valid CSS!
Page created in 0.437 seconds with 45 queries.

Google visited last this page August 30, 2010, 01:59:59 AM