i have a class which reads the list available in particular location,
the following is my code,
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExceptionInFileHandling {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void GetDirectory(String a_Path, List a_files, List a_folders) throws IOException {
try {
File l_Directory = new File(a_Path);
File[] l_files = l_Directory.listFiles();
for (int c = 0; c < l_files.length; c++) {
if (l_files[c].isDirectory()) {
a_folders.add(l_files[c].getName());
} else {
a_files.add(l_files[c].getName());
}
}
} catch (Exception ex){
ex.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
public static void main(String args[]) throws IOException {
String filesLocation = "asdfasdf/sdfsdf/";
List l_Files = new ArrayList(), l_Folders = new ArrayList();
GetDirectory(filesLocation, l_Files, l_Folders);
System.out.println("Files");
System.out.println("---------------------------");
for (Object file : l_Files) {
System.out.println(file);
}
System.out.println("Done");
}
}
in this the file path can be passed as argument and that should be taken up based on the OS,
filePath.replaceAll("\\\\|/", "\\" + System.getProperty("file.separator"))
is this correct?
// Don't do this
filePath.replaceAll("\\\\|/", "\\" + System.getProperty("file.separator"))
import java.nio.file.*;
Path path = Paths.get(somePathString);
// Here is your system independent path
path.toAbsolutePath();
// Or this works too
Paths.get(somePathString).toAbsolutePath();
// You can also input a String that has a proper file seperator like so
String filePath = "SomeDirectory" + File.separator;
// Then call your directory method
try{
ExceptionInFileHandling.GetDirectory(filePath, ..., ...);
} catch (Exception e){}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void GetDirectory(String a_Path, List a_files, List a_folders) throws IOException {
try {
// File object is instead constructed
// with a URI by using Path.toUri()
// Change is done here
File l_Directory = new File(Paths.get(a_Path).toUri());
File[] l_files = l_Directory.listFiles();
for (int c = 0; c < l_files.length; c++) {
if (l_files[c].isDirectory()) {
a_folders.add(l_files[c].getName());
} else {
a_files.add(l_files[c].getName());
}
}
} catch (Exception ex){
ex.printStackTrace();
}
}
You can use forward slashes as directory separators on Windows as well when calling File constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With