Stringvariabile contiene un nome di file, C:\Hello\AnotherFolder\The File Name.PDF. Come posso ottenere solo il nome del file The File Name.PDFcome stringa?
Ho pianificato di dividere la stringa, ma questa non è la soluzione ottimale.
Stringvariabile contiene un nome di file, C:\Hello\AnotherFolder\The File Name.PDF. Come posso ottenere solo il nome del file The File Name.PDFcome stringa?
Ho pianificato di dividere la stringa, ma questa non è la soluzione ottimale.
Risposte:
basta usare File.getName ()
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());
usando i metodi String :
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));
Utilizzo alternativo Path(Java 7+):
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();
Si noti che la divisione della stringa \\dipende dalla piattaforma in quanto il separatore di file potrebbe variare. Path#getNamesi occupa di quel problema per te.
Paths.getacceda al file system, quindi non mi aspetto che le prestazioni siano materialmente diverse da una sottostringa / indexOf.
Internet Explorere ha il percorso "C:\\Hello\\AnotherFolder\\The File Name.PDF"ma il tuo codice funziona su una macchina Unix / Linux quindi p.getFileName()restituirà l'intero percorso, non solo The File Name.PDF.
toString()è così imbarazzante.
Utilizzando FilenameUtilsin Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
Considerando Stringche stai chiedendo è
C:\Hello\AnotherFolder\The File Name.PDF
dobbiamo estrarre tutto dopo l'ultimo separatore, ad es. \. Questo è ciò a cui siamo interessati.
Tu puoi fare
String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);
Questo recupererà l'indice dell'ultimo \nel tuo Stringed estrarrà tutto ciò che viene dopo fileName.
Se si dispone di un Stringcon un separatore diverso, regolare lastIndexOfper utilizzare quel separatore. (C'è anche un sovraccarico che accetta un intero Stringcome separatore.)
L'ho omesso nell'esempio sopra, ma se non sei sicuro da dove Stringprovenga o cosa possa contenere, vorrai confermare che lastIndexOfrestituisce un valore non negativo perché Javadoc afferma che restituirà
-1 se non si verifica tale evento
puoi usare path = C: \ Hello \ AnotherFolder \ TheFileName.PDF
String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());
/su unix e \`(AND THERE IS A BUG IN THE MARKDOWN PARSER HERE) on windows. You can't know. Use another solution like File` o Paths.
File.separatoranche dipendente dalla piattaforma? O funzionerebbe ... String strPath = path.substring(path.lastIndexOf(File.separator)+1, path.length());
File.separatornon funzionerà sempre qui perché in Windows un nome file può essere separato da "/"o "\\".
Le altre risposte non hanno funzionato abbastanza per il mio scenario specifico, in cui sto leggendo percorsi che hanno avuto origine da un sistema operativo diverso da quello attuale. Per elaborare sto salvando gli allegati e-mail salvati da una piattaforma Windows su un server Linux. Il nome file restituito dall'API JavaMail è simile a "C: \ temp \ hello.xls"
La soluzione con cui ho finito:
String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];
Considera il caso che Java sia multipiattaforma:
int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
fileName = fileName.substring(lastPath+1);
}
Un metodo senza alcuna dipendenza e si prende cura di ... , . e duplicatori separati.
public static String getFileName(String filePath) {
if( filePath==null || filePath.length()==0 )
return "";
filePath = filePath.replaceAll("[/\\\\]+", "/");
int len = filePath.length(),
upCount = 0;
while( len>0 ) {
//remove trailing separator
if( filePath.charAt(len-1)=='/' ) {
len--;
if( len==0 )
return "";
}
int lastInd = filePath.lastIndexOf('/', len-1);
String fileName = filePath.substring(lastInd+1, len);
if( fileName.equals(".") ) {
len--;
}
else if( fileName.equals("..") ) {
len -= 2;
upCount++;
}
else {
if( upCount==0 )
return fileName;
upCount--;
len -= fileName.length();
}
}
return "";
}
Caso di prova:
@Test
public void testGetFileName() {
assertEquals("", getFileName("/"));
assertEquals("", getFileName("////"));
assertEquals("", getFileName("//C//.//../"));
assertEquals("", getFileName("C//.//../"));
assertEquals("C", getFileName("C"));
assertEquals("C", getFileName("/C"));
assertEquals("C", getFileName("/C/"));
assertEquals("C", getFileName("//C//"));
assertEquals("C", getFileName("/A/B/C/"));
assertEquals("C", getFileName("/A/B/C"));
assertEquals("C", getFileName("/C/./B/../"));
assertEquals("C", getFileName("//C//./B//..///"));
assertEquals("user", getFileName("/user/java/.."));
assertEquals("C:", getFileName("C:"));
assertEquals("C:", getFileName("/C:"));
assertEquals("java", getFileName("C:\\Program Files (x86)\\java\\bin\\.."));
assertEquals("C.ext", getFileName("/A/B/C.ext"));
assertEquals("C.ext", getFileName("C.ext"));
}
Forse getFileName è un po 'confuso, perché restituisce anche i nomi delle directory. Restituisce il nome del file o dell'ultima directory in un percorso.
estrarre il nome del file usando java regex *.
public String extractFileName(String fullPathFile){
try {
Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
Matcher regexMatcher = regex.matcher(fullPathFile);
if (regexMatcher.find()){
return regexMatcher.group(1);
}
} catch (PatternSyntaxException ex) {
LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
}
return fullPathFile;
}
Metodo getFileName () di java.nio.file.Path utilizzato per restituire il nome del file o della directory puntato da questo oggetto percorso.
Percorso getFileName ()
Per riferimento:
https://www.geeksforgeeks.org/path-getfilename-method-in-java-with-examples/
È possibile utilizzare l'oggetto FileInfo per ottenere tutte le informazioni del file.
FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
MessageBox.Show(f.Name);
MessageBox.Show(f.FullName);
MessageBox.Show(f.Extension );
MessageBox.Show(f.DirectoryName);