File path issue with: / -> \

2019-07-27 11:34发布

            // 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_"))

3条回答
祖国的老花朵
2楼-- · 2019-07-27 11:37

\ 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 \'.

enter image description here

查看更多
小情绪 Triste *
3楼-- · 2019-07-27 11:44

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.

查看更多
做个烂人
4楼-- · 2019-07-27 12:02

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.

查看更多
登录 后发表回答