0

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
agarwal_achhnera
  • 2,582
  • 9
  • 55
  • 84
  • Please don't just copy and paste your question from some other site. At least go to the effort of formatting it correctly for StackOverflow. – Mark Peters Jul 23 '11 at 05:09
  • it is the problem which I my self facing in my project, the code is like above, but the actual code is very big which is a command line tool, Now I have perform the indentation – agarwal_achhnera Jul 23 '11 at 05:12

4 Answers4

2
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
Erre Efe
  • 15,387
  • 10
  • 45
  • 77
1

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;
}
Community
  • 1
  • 1
Tom
  • 43,583
  • 4
  • 41
  • 61
  • it works if folder does not exist,but with my code folder and the subfolders are created it does not give any exception if there is . after folder seperator \ and also if / exist in the path – agarwal_achhnera Jul 23 '11 at 05:30
1

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

agarwal_achhnera
  • 2,582
  • 9
  • 55
  • 84
0

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 a JFileChooser. 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!).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • NO I will work only threw command line, and if the given path string is wrong then I will just notice the user proper reason for not to creating the file like FAILED: outfile folder could not be created. or FAILED:invalid file name – agarwal_achhnera Jul 23 '11 at 05:34
  • I am still not sure if you are saying that (Swing) GUI elements are OK or not. In any case, I edited my answer with an example. Give it a try and see if it works for you. – Andrew Thompson Jul 23 '11 at 06:25
  • But I have to use only Command line tool, I can't use JFileChooser for this purpose. I just want to validation for the given path and file by java – agarwal_achhnera Jul 23 '11 at 07:15