Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a (String) location is a valid saving path in Java?

I am receiving a string from user which should be used as a location to save content to a file. This string should contain enough information, like a directory + file name.

My question is, how can I check whether the provided string is a valid path to save content to a file (at least in theory)?

It does not matter whether directories are created or not, or whether one has proper access to the location itself. I am only interested in checking the structure of the provided string.

How should I proceed? I was thinking about creating a File object, then extracting its URI. Is there any better way?

like image 645
Jérôme Verstrynge Avatar asked Dec 13 '22 11:12

Jérôme Verstrynge


2 Answers

You can use File.getCanonicalPath() to validate according the current OS rules.

import java.io.File;
import java.io.IOException;

public class FileUtils {
  public static boolean isFilenameValid(String file) {
    File f = new File(file);
    try {
       f.getCanonicalPath();
       return true;
    }
    catch (IOException e) {
       return false;
    }
  }

  public static void main(String args[]) throws Exception {
    // true
    System.out.println(FileUtils.isFilenameValid("well.txt"));
    System.out.println(FileUtils.isFilenameValid("well well.txt"));
    System.out.println(FileUtils.isFilenameValid(""));

    //false
    System.out.println(FileUtils.isFilenameValid("test.T*T"));
    System.out.println(FileUtils.isFilenameValid("test|.TXT"));
    System.out.println(FileUtils.isFilenameValid("te?st.TXT"));
    System.out.println(FileUtils.isFilenameValid("con.TXT")); // windows
    System.out.println(FileUtils.isFilenameValid("prn.TXT")); // windows
    }
  }
like image 130
RealHowTo Avatar answered May 19 '23 08:05

RealHowTo


Have you looked at Apache Commons IO? This library includes various things for handling path information which may help e.g. FilenameUtils.getPath(String filename) which returns the path from a full filename.

like image 36
fipple Avatar answered May 19 '23 08:05

fipple