Reputation: 11
How do we split a file path for example
String path=file:\C:\Users\id\work\target\test-classes\ean\sample.txt
to
String filePath=file:\C:\Users\id\work\target\test-classes\ean\
String filename=sample.txt
The functionality required is to use
Paths.get(filePath,filename)
Upvotes: 1
Views: 626
Reputation: 161
If you create a FileInfo object from your file (add using System.IO) you can use the FullName property with Replace() to get the path, and the Name property for the name.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace Generic_Unit_Tests
{
[TestClass]
public class FileAndPathTest
{
[TestMethod]
public void GetFileNameAndPathTest()
{
string fullFileName = @"C:\Users\joey\Documents\Visual Studio 2012\Projects\Repo Docs and Notes\TestFile.txt";
string filePath = string.Empty;
string fileName = string.Empty;
FileInfo fi = new FileInfo(fullFileName);
filePath = fi.FullName.Replace(fi.Name, string.Empty);
fileName = fi.Name;
Console.WriteLine(string.Format("Path: {0}", filePath));
Console.WriteLine(string.Format("File Name: {0}", fileName));
}
}
}
And the result:
Test Name: GetFileNameAndPathTest
Test Outcome: Passed
Result StandardOutput:
Path: C:\Users\joey\Documents\Visual Studio 2012\Projects\Repo Docs and Notes\
File Name: TestFile.txt
And Bob's your uncle.
Joey
Upvotes: 0
Reputation: 8324
You can use file.getParent() to get the directory path.
And file.getName() to get the file name.
Upvotes: 1