Searching the occurrence of \
I have a String
that stores a path. When I print the path, it is like: D:\UnderTest\wavtester.wav
. In this string I wanted to know the index of the last occurrence of \
character (the goal is to get the name of the file represented in the String
), so开发者_JAVA技巧 I tried to use the method:
int x = nameOfAudioFile.lastIndexOf('\');
But I get an error corresponding to this statement saying : unclosed character literal
- What does this error mean?
- How can I solve this error?
The \
character has special functions in character and string constant, so you need to escape it in order to write it itself as a character literal: string.lastIndexOf('\\')
.
Acatually, in order to be portable you probably want to use File.separatorChar
instead of an explicit character constant. That way you'll get /
on unix instead of \
.
import java.io.File;
class FileString {
public static void main(String[] args) {
String fileName = "D:\\UnderTest\\wavtester.wav";
System.out.println(fileName);
File f = new File(fileName);
System.out.println("Name: \t" + f.getName());
System.out.println("Path: \t" + f.getParent());
System.out.println("Exist: \t" + f.exists());
}
}
Output
D:\UnderTest\wavtester.wav
Name: wavtester.wav
Path: D:\UnderTest
Exist: false
Press any key to continue . . .
Disclaimer
This is not an answer to your question, it is not even an answer to the question, but merely the best suggestion I can provide in lieu of knowing what the actual question is. ;)
You need to add another \. You're escaping the ' with the single \, so it you should look like; nameOfAudioFile.lastIndexOf('\\')
精彩评论