How to split a file path with path and name seperated - java

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)

You can use file.getParent() to get the directory path.
And file.getName() to get the file name.

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

Related

How to get subdirectory name from string path in java

I want to get "to" from the below string which is the path of a file.
String path="/Path/to/Text.txt";
String path="/The/Path/to/Text.txt";
How do i get the subdirectory name "to"?
Java has a library class to work with files. It is called File (surprisingly...):
import java.io.File;
//...
File file= new File("/Path/to/Text.txt");
File parentDir = file.getParent();
System.out.println(parentDir.getName());
You can use Path class:
Path p = Paths.get("/The/Path/to/Text.txt");
System.out.println(p.getParent()); // /The/Path/to
System.out.println(p.getParent().getFileName()); // to
System.out.println(p.getName(2)); // to
If your path is a String:
String[] directories = path.split("/");
System.out.println(directories[directories.length-2]);
But remember to check your path length to avoid indexOutOfBounds

Is it possible to assign a String variable the absolute path of a File?

I am wondering if it is possible to assign a String Variable the path of the file? If Yes, then is it possible to update the File Dynamically?
I am trying to create Files dynamically (which I am able to do so), but I want to link these dynamically created files to a String variable.
Please help. Thanks in advance.
File dir = new File("Data");
if(!dir.exists()){
dir.mkdir();
}
String filename = "file1";
File tagfile = new File(dir, filename+".txt");
if(!tagfile.exists()){
tagfile.createNewFile();
}
System.out.println("Path : " +tagfile.getAbsolutePath());
String s = new File("xyz.txt").getAbsolutePath();
or
String s = new File("xyz.txt").getCanonicalPath();
Both of the above assign (in my case) c:\dev\xyz.txt to the string s.
To get the full system path windows or linux
public static void main(String []args){
String path = "../p.txt";//works on windows or linux, assumes you are not in root folder
java.io.File pa1 = new java.io.File (path);
String s = null;
try {
s = pa1.getCanonicalFile().toString();
System.out.println("path " + s);
} catch (Exception e) {
System.out.println("bad path " + path);
e.printStackTrace();
}
Prints out full path like c:\projects\file\p.txt
Here is the code to do that:
File file = new File("C:\\testfolder\\test.cfg");
String absolutePath = file.getAbsolutePath();
This is what javadoc says about the getAbsolutePath API:
getAbsolutePath
public String getAbsolutePath() Returns the absolute pathname string
of this abstract pathname. If this abstract pathname is already
absolute, then the pathname string is simply returned as if by the
getPath() method. If this abstract pathname is the empty abstract
pathname then the pathname string of the current user directory, which
is named by the system property user.dir, is returned. Otherwise this
pathname is resolved in a system-dependent way. On UNIX systems, a
relative pathname is made absolute by resolving it against the current
user directory. On Microsoft Windows systems, a relative pathname is
made absolute by resolving it against the current directory of the
drive named by the pathname, if any; if not, it is resolved against
the current user directory.
Returns: The absolute pathname string denoting the same file or
directory as this abstract pathname

Get filename without extension from full path [duplicate]

This question already has answers here:
How to get the filename without the extension in Java?
(22 answers)
Closed 7 years ago.
I am making a program to store data from excel files in database. I would like the user to give in console the full path of the file and after the program to take only the file name to continue.
The code for loading the full path is:
String strfullPath = "";
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the fullpath of the file");
strfullPath = scanner.nextLine();
String file = strfullPath.substring(strfullPath.lastIndexOf('/') + 1);
System.out.println(file.substring(0, file.indexOf('.')));
After that I would like to have: String filename = .......
The full path that the user would type would be like this: C:\\Users\\myfiles\\Documents\\test9.xls
The filename that I would create would take only the name without the .xls!
Could anyone help me how I would do this?
How i would do it if i would like to take as filename "test9.xls" ? –
You can do it like this:
String fname = file.getName();
int pos = fname.lastIndexOf(".");
if (pos > 0) {
fname = fname.substring(0, pos);
}
or you can use the apache.commons.io.FilenameUtils:
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
I usually use this solution described in other post:
import org.apache.commons.io.FilenameUtils;
String basename = FilenameUtils.getBaseName(fileName);
You could use the File class to get the file name:
File userFile = new File(strfullPath);
String filename = userFile.getName();
Using a File object has numerous benefits, including the ability to test the file exists:
if (userFile.isFile()) {
// Yay, it's a valid file (not a directory and not an invalid path)
}
You also need to check the file has an extension before you try and strip it:
if (filename.indexOf(".") > 0) {
filename = filename.substring(0, filename.lastIndexOf("."));
}
You can call the file.getName() method that returns the name of the file as String. Then you cut the extension.
String fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf(".")+1);
if (!filename.equals(""))
{
String [] fileparts = filename.split("\\.");
String filename = fileparts[0]; //Get first part
}

Java String as Part if a Path

I would like to have a directory path that is A/%Name%/B, where %Name% is a string I declared earlier, is there a Path.Combine like in C#? Or what could I use?
If I understand it correctly , you are trying to format a String.
You can use
String directoryName = "test";
String path = "A/%s/B";
String.format(path,directory);
or something like below based on your requirement
File f = new File(String.format(path,directory));
You can use:
String yourString = ...;
File theFile = new File("A/" + yourString + "/B");
Use the File constructor:
File combined = new File(new File("A", name), "B");
You could even write a convenience method to do that if you wanted:
public static File combine(String base, String... sections)
{
File file = new File(base);
for (String section : sections) {
file = new File(file, section);
}
return file;
}
Then you can call it as:
File x = combine("A", name, "B");
Note that using the File constructor like this is generally considered preferable to assuming a directory separator of /, even though in practice that works on all platforms that I'm aware of.

How to get FolderName and FileName from the DirectoryPath

I have DirectoryPath:
data/data/in.com.jotSmart/app_custom/folderName/FileName
which is stored as a String in ArrayList
Like
ArrayList<String> a;
a.add("data/data/in.com.jotSmart/app_custom/page01/Note01.png");
Now from this path I want to get page01 as a separate string and Note01 as a separate string and stored it into two string variables. I tried a lot, but I am not able to get the result. If anyone knows help me to solve this out.
f.getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
For example
File f = new File("/home/jigar/Desktop/1.txt");
System.out.println(f.getParent());// /home/jigar/Desktop
System.out.println(f.getName()); //1.txt
Update: (based on update in question)
if data/data/in.com.jotSmart/app_custom/page01/Note01.png is valid representation of file in your file system then
for(String fileNameStr: filesList){
File file = new File(fileNameStr);
String dir = file.getParent().substring(file.getParent().lastIndexOf(File.separator) + 1);//page01
String fileName = f.getName();
if(fileName.indexOf(".")!=-1){
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}
}
For folder name: file.getParentFile().getName().
For file name: file.getName().
create a file with this path...
then use these two methods to get directory name and file name.
file.getParent(); // dir name from starting till end like data/data....../page01
file.getName(); // file name like note01.png
if you need directory name as page01, you can get a substring of path u got from getparent.
How about using the .split ?
answer = str.split(delimiter);

Categories

Resources