File path issue with: / -> \

旧巷老猫 提交于 2020-01-06 01:58:30

问题


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

these lines are in a recursive method. first time it gives right path:

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

But on the second call it flips the forward slash to back slash:

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

it works fine if I do not use the condition.

if(path.contains("channel_"))

回答1:


\ is called as Escape sequence in java which is used in various purposes .

In your case use 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;

Use double slash \\ ! It's a special escape pattern. Like \n or \r.
Escape sequence normally used in text files in Windows, specially in notepad.

The primary Java escape sequences are listed below. They are used to represent non-graphical characters and also characters such as double quotes, single quotes, and backslashes. If you'd like to represent a double quote within a String literal, you can do so with \". If you'd like to represent a single quote within a character literal, you can do so with \'.




回答2:


That is because the File.seperator in Windows is \. Every time you let your path String go through a java.io.File it will replace them. So to fix this, either don't use File as auxiliary tool, or replace the backslashes with forward slashes.

So, what happens is that your path String uses backward slashes. You retrieve that String form a java.io.File which will automatically uses backslashes on Windows. If the path contains "channel_1", then you overwrite the whole string using a hardcoded string with forward slashes.




回答3:


In addition to the previous answers. You should not use / or \ hard coded in your application. Because this will harm the portability of your application. rather use,

File.separator

File#separator gives you, the separator depending in your system.



来源:https://stackoverflow.com/questions/17673745/file-path-issue-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!