简体   繁体   中英

substring using \(backslash) in java

I want to get file name from complete path of file. Input : "D://amol//1/\\15_amol.jpeg" Expected Output : 15_amol.jpeg

I have written below code for this

public class JavaApplication9 {
    public static void main(String[] args) {
        String fname="D://amol//1/\15_amol.jpeg";
        System.out.println(fname.substring(fname.lastIndexOf("/")));
        System.out.println(fname.substring(fname.lastIndexOf("\\")));
    }
}

but getting below output :

_amol.jpeg

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1   
  at java.lang.String.substring(String.java:1927)   
  at javaapplication9.JavaApplication9.main(JavaApplication9.java:6)

C:\Users\lakhan.kamble\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
 Java returned: 1

The string \\15 is an "octal escape" for the carriage return character (0x0d, 13 decimal). There are two possibilities here.

  1. You really meant \\15 to be the octal escape, in which case you are trying to create a filename with an embedded newline. The actual contents of fname in this case could be expressed as

     "D://amol//1/" + "\\n" + "_amol.jpeg"; 

    Windows will prevent that from happening and your program will throw an IOException .

  2. You really meant

     String fname="D://amol//1/\\\\15_amol.jpeg"; 

    In this case the extra backslash is redundant and will be ignored by Windows because the filename will resolve (in Windows path terms) to D:\\amol\\1\\\\15_amol.jpeg and adjacent directory separators collapse to a single separator. So you could just omit the extra backslash altogether without changing the effective path.

As to your exception, the string as shown DOES NOT contain a backslash character (case 1 above), so

fname.lastIndexOf("\\")

returned -1, causing the exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM