简体   繁体   中英

Managing absolute path and full path

I've created a small program wich can read a.txt file.

This file contains a link to another file in this format new_file.txt

The goal is to return the path of the new file, so basically I'm doing this:

String newFileName = getFileName();
int index = oldFilePath.lastIndexOf('\\');
String path = oldFilePath.substring(0, index + 1);
String newFilePath = path + newFileName;
return newFilePath;

For example:

The first file I opened is: C:\a\b\c\oldFile.txt

In this file I found newFile.txt

So the new path will be: C:\a\b\c\newFile.txt

Nice, but what If I find something like this:

..\ or .\.\ or ...

Is there any way to automate this mess?

Thanks

In C#/.Net you have the rather cool Path class .

You can use Path.GetFullPath( string pathname ) to resolve paths eg with \..\ etc in them.

Use Path.GetDirectory() , Path.GetFileName() , Path.GetFileNameWithoutExtension() & Path.GetExtension() to pull names apart and Path.Combine() to put them back together again.

You've tagged this as java as well as c#

In java look at FileNameUtils http://commons.apache.org/io/apidocs/org/apache/commons/io/FilenameUtils.html

The normalize method should help

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