开发者

How to get a desired substring form a String in java or jsf?

I am developing an application using开发者_开发技巧 JSF in Eclipse IDE with Derby as database. I have a feature to upload files to the database. But the file name is getting stored as "C:\Documents and Settings\Angeline\Desktop\test.txt" instead of "test.txt". How do I get to store only "test.txt" as file name in the database?

This is my code in JSF:

 File to Upload:

<t:inputFileUpload id="fileupload" value="#{employeeBean.upFile}" storage="file"/>

Java Bean Code:

 String fileName=upFile.getName();

The value of this fileName=C:\Documents and Settings\Angeline\Desktop\test.txt.


lastSlashIndex = name.lastIndexOf("\\");
if (lastSlashIndex == -1) {
    lastSlashIndex = name.lastIndexOf("/"); //unix client
}
String shortName = name;
if (lastSlashIndex != -1) {
    shortName = name.substring(lastSlashIndex);
}

Note that if the filename on *nix contain a \ this won't work.


new java.io.File(myPath).getName();

You could probably do something more efficient with only String operations but depending on the application load and other operations, it might not be worth it.


Tomahawk t:inputFileUpload is built on top of Apache Commons FileUpload and Apache Commons IO. In the FileUpload FAQ you can find an entry titled "Why does FileItem.getName() return the whole path, and not just the file name? " which contains the following answer:

Internet Explorer provides the entire path to the uploaded file and not just the base file name. Since FileUpload provides exactly what was supplied by the client (browser), you may want to remove this path information in your application. You can do that using the following method from Commons IO (which you already have, since it is used by FileUpload).

String fileName = item.getName();
if (fileName != null) {
    filename = FilenameUtils.getName(filename);
}

In short, just use FilenameUtils#getName() to get rid of the complete path which has been unnecessarily appended by MSIE (all the other real/normal webbrowsers doesn't add the complete client side path, but just provide the sole filename as per the HTML forms specs).

So, all you basically need to do is replacing

String fileName = upFile.getName();

by

String fileName = FilenameUtils.getName(upFile.getName());


I think it would be safer to see this not as a string manipulation problem, but as a path name parsing problem:

String filename = new File(pathname).getName()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜