【问题标题】:how to know invalid path to save the file in java如何知道在java中保存文件的无效路径
【发布时间】:2011-10-11 12:27:03
【问题描述】:

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

在执行程序之前(一个命令行工具),C:\ 目录中没有temp 文件夹,但是当我运行程序时它会创建temp 文件夹然后在@987654329 @ 它创建 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 中创建用户,然后在 user 文件夹中创建 fir,然后在其中创建 st.csv 文件。

【问题讨论】:

  • 请不要只是从其他网站复制和粘贴您的问题。至少要努力为 StackOverflow 正确格式化。
  • 这是我自己在项目中遇到的问题,代码如上,但实际代码很大,是一个命令行工具,现在我已经执行了缩进

标签: java file filesystems


【解决方案1】:

在我的情况下,我需要这个作品

if(!path.equals(file.getCanonicalPath())){ System.out.println("FAILED: 文件名、目录或卷标无效,语法错误"); System.exit(0); }

通过在
File file=new File(path);
之后添加此代码,它可以正常工作,并且如果给定路径不正确,它会通知用户


由于只有两个选项,java 将在某个路径上创建文件,该路径将是规范路径,或者如果无法创建文件,它将给出异常。所以如果用户给出的路径和规范路径有任何不匹配,则意味着用户输入了错误的路径,java无法在文件系统上创建,所以我们会注意到用户,或者如果java给出异常,那么我们可以捕获它并会注意到用户的路径不正确

【讨论】:

    【解决方案2】:

    你提到这是一个命令行工具。这是否意味着它将始终从命令行运行,或者可以从假定没有进一步用户交互的环境(如批处理文件或通过 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,而是在 JFrameJDialog 或(最简单的)@987654328 内的 JTextArea 中显示文本@,使用 JButton 调用保存编辑的文本。我的意思是,基于命令行的文件编辑器?这是第三个千年(该死!)。

    【讨论】:

    • 不,我只会扔命令行,如果给定的路径字符串错误,那么我只会注意到用户不创建文件的正当理由,如 FAILED:无法创建 outfile 文件夹。或失败:文件名无效
    • 我仍然不确定您是否说(Swing)GUI 元素是否正常。无论如何,我用一个例子编辑了我的答案。试一试,看看它是否适合你。
    • 但我只能使用命令行工具,我不能为此目的使用 JFileChooser。我只想通过 java 验证给定的路径和文件
    【解决方案3】:

    看起来与此非常相似: 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;
    }
    

    【讨论】:

    • 如果文件夹不存在,它可以工作,但是使用我的代码文件夹和子文件夹创建它不会给出任何异常。在文件夹分隔符 \ 之后,如果 / 存在于路径中
    【解决方案4】:
    boolean exists = (new File("filename")).exists();
    if (exists) {
        // File or directory exists
    } else {
        // File or directory does not exist
    }
    

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

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

    【讨论】:

    • 首先创建文件的代码不是重点吗?这不是故事的全部。
    • 只需附加路径分隔符部分。感谢您让我注意到。
    猜你喜欢
    • 2021-08-18
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多