5

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?

M A
  • 71,713
  • 13
  • 134
  • 174
Java Questions
  • 7,813
  • 41
  • 118
  • 176

10 Answers10

8

There are better ways to use file paths...

// Don't do this
filePath.replaceAll("\\\\|/", "\\" + System.getProperty("file.separator"))

Use java.nio.file.path:

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();

Use File.seperator:

// 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){}

So a simple change to your method will now work cross platform:

@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();
       }

   }
miiiiiitchko
  • 510
  • 4
  • 11
5

You can use forward slashes as directory separators on Windows as well when calling File constructor.

Matej
  • 6,004
  • 2
  • 28
  • 27
  • i am sorry and dont really get you, please add some examples – Java Questions Nov 18 '14 at 09:53
  • @JavaQuestions you just need no modifications to your code. The path `asdfasdf/sdfsdf/` will be regarded as directory `sdfsdf` inside directory `asdfasdf` inside current directory. On any platform. You should not replace `/` for backslash on Windows. – Suzan Cioc Nov 26 '14 at 21:51
2

why you are not adding java defined file separator instead of creating a string then replacing all. try it like

String filesLocation = "asdfasdf"+File.separator+"sdfsdf"+File.separator;
Sindhoo Oad
  • 1,194
  • 2
  • 13
  • 29
0

The answer from you should be correct. There is another similiar thread with answer :

Java regex to replace file path based on OS

Platform independent paths in Java

Community
  • 1
  • 1
HaRLoFei
  • 316
  • 1
  • 8
0

First, you should not used relative path like asdfasdf/sdfsdf/. It's a big source of bugs as your path depends on your working directory.

That thing said, your replaceAll is quite good but it can be improved like this :

filePath.replaceAll(
    "[/\\\\]+",
    Matcher.quoteReplacement(System.getProperty("file.separator")));

Using quoteReplacement is adviced in replaceAll documentation

Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.

ToYonos
  • 16,469
  • 2
  • 54
  • 70
0

You could generate a Path object from the passed argument. Then you would not need to handle the file separator on your own.

public static void main(String[] args) {
    Path path = Paths.get(args[0]);
    System.out.println("path = " + path.toAbsolutePath());
}

The code is able to handle following passed arguments.

  • foo\bar
  • foo/bar
  • foo\bar/baz
  • foo\\bar
  • foo//baz
  • foo\\bar//baz
  • ...
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
0

You need to use java.io.File.separatorChar to The system-dependent default name-separator character.

String location = "usr"+java.io.File.separatorChar+"local"+java.io.File.separatorChar;

Vishvesh Phadnis
  • 2,448
  • 5
  • 19
  • 35
0

org.apache.commons.io.FilenameUtils contains a lot of useful methods, for instance separatorsToSystem(String path) converts separators in given path in accordance with OS which you are using.

Grigory
  • 465
  • 5
  • 16
0

Use the below method to know about OS file separator and then replaceAll previous separator with this methods.

System.getProperty("file.separator");
0

Why you just dont use "/". It is acceptable for both linux and windows as path seperator.

Adem
  • 9,402
  • 9
  • 43
  • 58