Francisco
Francisco

Reputation: 11

How to get only the name of my PDF file

I'm developing a project for college which consist reading a CSV file and converting that to a PDF file. That part is fine, I have already done that.

In the end I need to show the name of the PDF file without the full path of where it was created. In other words, I just want the to show the name.

I search a lot to see if there is a simple method that show the name like Java has to show only the name of the File like

file.getName();

Upvotes: 0

Views: 2234

Answers (2)

Amedee Van Gasse
Amedee Van Gasse

Reputation: 7634

Use getBaseName in Apache Commons IO.

getBaseName

public static String getBaseName(String filename)

Gets the base name, minus the full path and extension, from a full filename.

This method will handle a file in either Unix or Windows format. The text after the last forward or backslash and before the last dot is returned.

a/b/c.txt --> c
a.txt --> a
a/b/c --> c
a/b/c/ --> "" 

The output will be the same irrespective of the machine that the code is running on.

Parameters:

  • filename - the filename to query, null returns null

Returns:

  • the name of the file without the path, or an empty string if none exists. Null bytes inside string will be removed

Source: https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getBaseName(java.lang.String)

If you also need the extension, use getExtension. Which would probably always be .pdf, but you know, it's perfectly valid to have a PDF file without the .pdf filename extension. No sane person would do that but it is better to be prepared for insane users.

Upvotes: 1

mkl
mkl

Reputation: 96029

Whenever you use iText to create a PDF file, your code sets the target which usually is an OutputStream. If you use a FileOutputStream there, you know the file it writes to.

Thus, all you have to do to to show the name of the PDF File is to inspect your own code and check which target it sets.

Upvotes: 1

Related Questions