Reputation: 2157
My problem statement is as below:
1) I have a path till a folder. I have to traverse using that path. Check whether there are any subfolders and files in that path. If yes, match the contents of the folder(Lists) with the array. If it matches take it as a new path.
2) Using new path. List down the files in that path.
I am able to do everything except comparing lists
and array
. Below is my code:
import java.text.SimpleDateFormat
import java.util.Calendar
import java.io.File
class ListingDirectories {
def getListOfDirectories(dir: String): List[File] = {
val d = new File(dir)
if (d.exists && d.isDirectory) {
d.listFiles().filter(_.isDirectory()).toList
} else {
List[File]()
}
}
def getListOfFiles(dir: String): List[File] = {
val d = new File(dir)
if (d.exists && d.isDirectory()) {
d.listFiles().filter(_.isFile()).toList
} else {
List[File]()
}
}
}
object FirstSample {
def main(args: Array[String]) {
val ld = new ListingDirectories()
val directoriesList = ld.getListOfDirectories("C:/Users/Siddheshk2/Desktop/CENSUS").toList
println(directoriesList + "\n")
val directoriesListReplaced = directoriesList.toString().replace("//", "/")
// println(directoriesListReplaced.indexOf("C:/Users/Siddheshk2/Desktop/CENSUS/SAMPLE"))
var finalString = ""
var s = Array("C:/Users/Siddheshk2/Desktop/CENSUS/SAMPLE")
for (x <- s) {
if (x.equals(directoriesListReplaced)) {
finalString = s(0)
} else {
println("No matching strings")
}
}
val filesList = ld.getListOfFiles(finalString)
println(filesList.toString())
}
}
I just need to compare the values from the list and array and take it as a new path in finalString
variable in order to pass in the next method which is getListOfFiles
. I figured out since I am returning List[file]
in methods I am not able to access the elements inside it. Can anyone help me to understand where am I going wrong? TIA
Upvotes: 0
Views: 65
Reputation: 2157
After lot of struggle, I solved it using below code:
import java.io.File
object PlayingWithLists {
def main(ar: Array[String]) {
var s = "C:/Users/Siddheshk2/Desktop/CENSUS/SAMPLE2"
var finalValue = ""
var valuesReplaced = ""
var filePath = ""
for (file <- new File("C:/Users/Siddheshk2/Desktop/CENSUS").listFiles) {
valuesReplaced = file.toString.replace("\\", "/")
if (valuesReplaced.contains(s.trim)) {
finalValue = file.toString
} else {
}
}
for (file <- new File(finalValue).listFiles) {
filePath = file.toString.trim
}
}
}
Upvotes: 0
Reputation: 170899
Your directoriesListReplaced
will be a string which looks like "List(C:/Users/Siddheshk2/Desktop/CENSUS/SAMPLE,C:/Users/Siddheshk2/Desktop/CENSUS/SAMPLE1,C:/Users/Siddheshk2/Desktop/CENSUS/SAMPLE2)"
and s
won't equal it. It isn't at all clear what you want to do with directoriesListReplaced
; maybe it should just be
for (x <- s) {
if (directoriesList.contains(x)) {
...
} else {
println("No matching strings")
}
}
Upvotes: 1