2011-07-23 141 views
0

在Java中我想创建一个文件并在其上保存数据。带有路径的File名称取自用户。现在,如果用户给出无效路径,如C:\temp\./user\fir/st.csv这是一条无效路径,因为"."/在路径中,而在Windows操作系统"\"被用作路径分隔符。如何知道在java中保存文件的无效路径

执行程序(一命令行工具)之前,没有temp文件夹中C:\目录,但是当我运行该程序会创建temp文件夹,然后在temp它创建user然后在user它创建fir文件夹终于在st.csv里面。虽然我希望如果用户用户给出这种类型的无效路径或文件名应通过消息"Invalid path or file name"注意。

我该怎么办?程序代码如下图所示:

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

现在,如果我给作为C:\tump\./user\fir/st.csv那么它在C驱动器tump创建tump文件夹,然后用户,然后在firuser然后st.csv文件在它的路径。

+0

请不要仅从您的其他站点复制并粘贴您的问题。至少要为StackOverflow正确设置格式。 –

+0

这是我自己在我的项目中遇到的问题,代码如上,但实际的代码非常大,这是一个命令行工具,现在我执行缩进 –

回答

0

在我来说,我需要这个工作

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

通过添加该代码刚过
档案文件=新的文件(路径);
它会正常工作,如果给定的路径是不正确


由于只有两个选择要么java会创建一些路径上的文件,这将是规范的路径,或者无法创建文件它将会注意到用户给予例外。所以如果用户给出的路径和规范路径有任何不匹配的地方,那么它意味着用户类型错误的路径,而java不能在文件系统上创建,所以我们会注意到用户,或者如果java给出异常,那么我们可以捕获它并会通知用户路径不正确

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

PLUS:您绝不能使用硬编码的路径分隔符。你具有的问题,改用静态属性

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

Clear&Concise! –

+0

首先创建文件的代码不是整个代码?这不是整个故事。 –

+1

只需追加路径分隔符部分即可。感谢您让我注意。 –

1

看起来很类似: Is there a way in Java to determine if a path is valid without attempting to create a file?

有一个在其中一个答案在这里的链接: http://www.thekua.com/atwork/2008/09/javaiofile-setreadonly-and-canwrite-broken-on-windows/

哪详细可能为你工作: 通过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; 
} 
+0

它工作如果文件夹不存在,但与我的代码文件夹和子文件夹创建它不会给任何例外,如果有。在文件夹分隔符\后,如果/存在路径 –

0

你提到这是一个命令行工具。这是否意味着它将始终从命令行运行,还是可以从假定没有进一步用户交互的环境(如批处理文件或Ant)中调用?

从命令行可以弹出一个JFileChooser。这是接受用户文件名的好方法。对用户来说更容易,对程序更可靠。

这是基于你的代码的例子:

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.."); 
     } 
     } 
    }); 
    } 
} 

需要注意的是,如果我被编码这一点,我会再继续摆脱InputStreamReader的,而是显示在JTextArea内文JFrame,JDialog或(最简单)JOptionPaneJButton调用保存编辑的文本。我的意思是,一个基于命令行的文件编辑器?这是千禧一代(该死的!)。

+0

否我只会工作扔命令行,如果给定的路径字符串是错误的,那么我会注意到用户没有创建文件的正确原因,如FAILED:outfile文件夹无法创建。或失败:文件名无效 –

+0

我仍然不确定您是否说(Swing)GUI元素是否正常。无论如何,我用一个例子编辑了我的答案。试一试,看看它是否适合你。 –

+0

但是我只能使用命令行工具,我不能使用JFileChooser来达到这个目的。我只是想通过java验证给定的路径和文件 –

相关问题