简体   繁体   中英

how to know invalid path to save the file in java

In Java I want to create a file from and save the data on it. The File name with path is taken from user. Now if user give invalid path like C:\temp\./user\fir/st.csv which is an invalid path because "." and / are in the path and on windows operating system "\" is used as path separator.

Before executing the program(a command line tool), there was no temp folder in C:\ directory, but when I run the program it creates temp folder then in temp it creates user then in user it create fir folder and finally st.csv in it. While I want that if such type of invalid path or file name is given by the user user should be noticed by message "Invalid path or file name" .

What should I do? Program code is like below:

public class FileTest {
    public static void main(String args[]) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Please enter path:");
            String path = br.readLine();
            File file = new File(path);
            String path1 = file.getParent();
            File file2 = new File(path1);
            if (!file2.exists()) {
                System.out.println("Directory does not exist , So creating directory");
                file2.mkdirs();
            }
            if (!file2.exists()) {
                System.out.println("Directory can not be created");
            } else {
                FileWriter writer = new FileWriter(file);
                PrintWriter out = new PrintWriter(writer);
                System.out.println("Please enter text to write on the file, print exit at new line to if finished");
                String line = "";
                while ((line = br.readLine()) != null) {
                    if (line.equalsIgnoreCase("exit")) {
                        System.out.println("Thanks for using our system");
                        System.exit(0);
                    } else {
                        out.println(line);
                        out.flush();
                    }
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Now if I give the path as C:\tump\./user\fir/st.csv then it create tump folder in C drive, then user in tump , then fir in user folder then st.csv file in it.

boolean exists = (new File("filename")).exists();
if (exists) {
    // File or directory exists
} else {
    // File or directory does not exist
}

PLUS: You must never use hard-coded path separators. You're having problems by that, use instead the static attributes

File.separator - string with file separator
File.separatorChar - char with file separator 
File.pathSeparator - string with path separator
File.pathSeparatorChar - char with path separator

Looks very similar to this: Is there a way in Java to determine if a path is valid without attempting to create a file?

There's a link in one of the answers to here: http://www.thekua.com/atwork/2008/09/javaiofile-setreadonly-and-canwrite-broken-on-windows/

Which details what could possibly work for you: By Peter Tsenga

public static boolean canWrite(String path) {
    File file = new File(path);
    if (!file.canWrite()) {
        return false;
    }
    /* Java lies on Windows */
    try {
        new FileOutputStream(file, true).close();
    } catch (IOException e) {
        LOGGER.info(path + ” is not writable: ” + e.getLocalizedMessage());
        return false;
    }
    return true;
}

You mention this is a command line tool. Does that mean it will be always run from the command line, or could it be called from an environment that presumes no further user interaction (like batch file or by Ant)?

From a command line, it is possible to pop aJFileChooser . This is a much better way to accept a file name from the user. It is easier for the user, and more reliable for the program.

Here is an example based on your code:

import java.io.*;
import javax.swing.*;

public class FileTest {

  public static void main(String args[]) {
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        JFileChooser fileChooser = new JFileChooser();
        int returnVal = fileChooser.showOpenDialog(null);
        if (returnVal==JFileChooser.APPROVE_OPTION) {
          File file = fileChooser.getSelectedFile();
          try {
            if (!file.getParentFile().exists()) {
              System.out.println("Directory does not exist, creating..");
              file.getParentFile().mkdirs();
            }
            if (!file.getParentFile().exists()) {
              System.out.println("Directory can not be created");
            } else {
              BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
              FileWriter writer = new FileWriter(file);
              PrintWriter out = new PrintWriter(writer);
              System.out.println("Please enter text to write on the file," +
                " print exit at new line to if finished");
              String line = "";
              while ((line = br.readLine()) != null) {
                if (line.equalsIgnoreCase("exit")) {
                  System.out.println("Thanks for using our system");
                  System.exit(0);
                } else {
                  out.println(line);
                  out.flush();
                }
              }
            }
          }
          catch (IOException e) {
            e.printStackTrace();
          }
        } else {
          System.out.println("Maybe next time..");
        }
      }
    });
  }
}

Note that if I were coding this, I'd then go on to get rid of the InputStreamReader and instead show the text in a JTextArea inside a JFrame , JDialog or (easiest) JOptionPane , with a JButton to invoke saving the edited text. I mean, a command line based file editor? This is the 3rd millennium (damn it.).

In my case which I required this works

if(!path.equals(file.getCanonicalPath())){
                System.out.println("FAILED:Either invalid filename, directory or volume label , syntax error");
                System.exit(0);
            }

By adding this code just after
File file=new File(path);
it will work fine and will notice the user if given path is incorrect


As there is only two options either java will create the file on some path which will be canonical path or if not able to create the file it will give exception. So if there is any mismatch in the path given by the user and canonical path then it means user type wrong path which java can not create on the file system, so we will notice the user, or if java give exception then we can catch it and will notice the user for incorrect path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM