【问题标题】:File path issue with: / -> \文件路径问题:/ -> \
【发布时间】:2013-07-14 11:15:07
【问题描述】:
            // Dividend Limit check or increase the Dividend
        if (dival == 10) {
            writer.println("Divident has reached it Limit !");
            i++;
            // update the file name
            String upath = "channel_" + i;
            System.out.println(path);
            // find channel_1 and replace with the updated path
            if (path.contains("channel_1")) {
                path = "D:/File Compression/Data/low_freq/low_freq/house_1/"
                        + upath + ".dat";
            } else {
                JOptionPane.showMessageDialog(null, "Invalid File Choosen");
                System.exit(0);
            }

            dival = 10;

        } else {
            dival = dival + 10;
            writer.println("Dividen:" + dival);
        }

这些行采用递归方法。第一次给出正确的路径:

D:/File Compression/Data/low_freq/low_freq/house_1/channel_2.dat

但在第二次调用时,它会将正斜杠翻转为反斜杠:

D:\File Compression\Data\low_freq\low_freq\house_1\channel_1.dat

如果我不使用条件,它可以正常工作。

if(path.contains("channel_"))

【问题讨论】:

  • 您发布的代码没有出现这个问题。 “路径”从何而来? NB 从来没有必要在 Java 文件名中使用反斜杠。
  • @EJP 路径来自字符串路径是静态的,它在其他类中,所以我从类名中调用它并在此处使用该路径。这是代码public void actionPerformed(ActionEvent arg0) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "Data File", "dat"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(getParent()); if (returnVal == JFileChooser.APPROVE_OPTION) { path = chooser.getSelectedFile().getAbsolutePath(); } }

标签: java string file path


【解决方案1】:

\在java中被称为转义序列,有多种用途。

在你的情况下使用File.separator

String path = "D:"+File.separator+"File Compression"+File.separator+"Data"+File.separator+"low_freq"+File.separator+"low_freq"+File.separator+"house_1"+File.separator;

使用双斜杠 \\ !这是一种特殊的逃生模式。像 \n 或 \r。
转义序列通常用于 Windows 中的文本文件,特别是在记事本中。

下面列出了主要的 Java 转义序列。它们用于表示非图形字符以及双引号、单引号和反斜杠等字符。如果您想在字符串文字中表示双引号,可以使用 \"。如果您想在字符文字中表示单引号,可以使用 \'。

【讨论】:

    【解决方案2】:

    除了前面的答案。您不应在应用程序中使用硬编码的/\。因为这会损害您的应用程序的可移植性。而是使用,

    File.separator
    

    File#separator 为您提供,分隔符取决于您的系统。

    【讨论】:

      【解决方案3】:

      那是因为 Windows 中的 File.seperator\。每次您让路径字符串通过java.io.File 时,它都会替换它们。所以要解决这个问题,要么不要使用 File 作为辅助工具,要么用正斜杠替换反斜杠。

      所以,您的 path 字符串使用了反斜杠。您从 java.io.File 中检索该字符串,它将在 Windows 上自动使用反斜杠。如果路径包含“channel_1”,则使用带有正斜杠的硬编码字符串覆盖整个字符串。

      【讨论】:

      • 你知道这个问题的解决方法吗?
      • 代码没有显示它如何或在哪里通过 java.io.File,虽然。
      • 我知道。但据我所知,这种行为没有其他解释,所以我猜是缺少一部分代码。
      • 我正在使用 java.io.file
      • @MartijnCourteaux 实际上我这样做是因为我在不同的文件夹中有文件,所以我得到了路径,只需将“channel_1”替换为“channel_”+i,如果我对其进行硬编码,我将无法实现我的目标
      猜你喜欢
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 2012-04-07
      • 2014-01-19
      相关资源
      最近更新 更多