How to get FolderName and FileName from the DirectoryPath - java

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);

Related

Java, get full path of file and removing filename

I'm trying to get the directory path to a file. The issue I am having is getting the last \ or / of the directory. As this code is supposed to work on all operating systems, I can't seem to find any solution for this. Any help is appreciated.
My code so far:
System.out.print("Enter dir: ");
String path = kb.nextLine();
File pathes = new File(path);
String path2 = pathes.getParent();
path = path.substring(0, path.lastIndexOf("\\")+1);
System.out.println("PATH: " + path);
System.out.println("PATH2: "+path2);
My output is:
PATH: C:\Users\User\Desktop\test\
PATH2: C:\Users\User\Desktop\test
This is just test code and not the real code I'm working on.
EDIT
What I'm trying to get is
C:\Users\User\Desktop\test\
from
C:\Users\User\Desktop\test\test.txt
To get the absolute path to the parent directory you can do:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt");
String path = f.getParentFile().getAbsolutePath();
System.out.println(path);
Output:
C:\Users\User\Desktop\test
If you really want the trailing slash, then you can just append File.separator:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt ");
String path = f.getParentFile().getAbsolutePath() + File.separator;
System.out.println(path);
Output:
C:\Users\User\Desktop\test\

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

Hard coding part of the Path in Java

I have the following dir tree
C:\folder1\folder2\SPECIALFolders1\folder3\file1.img
C:\folder1\folder2\SPECIALFolders2\folder3\file2.img
C:\folder1\folder2\SPECIALFolders3\folder3\file3.img
C:\folder1\folder2\SPECIALFolders4\folder3\file4.img
C:\folder1\folder2\SPECIALFolders5\folder3\file5.img
I want to get to folder2, list all dirs in it (SpecialFolders) then retrieve the paths of those folders while adding (folder3) to their path
The reason I'm doing this is I want later to pass this path (paths) to a method to retrieve last modified files in folder3. I know there are way easier ways to do it but this is a very particular case.
I'm also trying to retrieve those folders within a specific time range so I used a while loop for that
Date first = dateFormat.parse("2015-6-4");
Calendar ystr = Calendar.getInstance();
ystr.setTime(first);
Date d = dateFormat.parse("2015-6-1");
Calendar last = Calendar.getInstance();
last.setTime(d);
while(last.before(ystr))
{
//fullPath here = "C:\folder1\folder2\"
File dir = (new File(fullPath));
File[] files = dir.listFiles();
for (File file : files)
{
//Retrieve Directories only (skip files)
if (file.isDirectory())
{
fullPath = file.getPath();
//last.add(Calendar.DATE, 1);
System.out.println("Loop " + fullPath);
}
}
}
fullPath += "\\folder3\\";
return fullPath;
The problem with my code is that it only returns one path (that's the last one in the loop) --which make sense but I want to return all of the paths like this
C:\folder1\folder2\SPECIALFolders1\folder3\
C:\folder1\folder2\SPECIALFolders2\folder3\
C:\folder1\folder2\SPECIALFolders3\folder3\
C:\folder1\folder2\SPECIALFolders4\folder3\
C:\folder1\folder2\SPECIALFolders5\folder3\
I appreciate your input in advance
Instead of fullPath String, use for example ArrayList<String> to store all paths. Than instead of:
fullPath = file.getPath();
use:
yourArrayList.add(file.getPath());
Your method will return an ArrayList with all paths, and you will need to code a method to retrive all paths from it.

How to get the file names present in a particular location mentioned

Can any one tell me how can I get the file names present in the particular location say
E:/abc_RESPONSE/Response_.
I tried to use The
java.io.File.getName()
method which returns the last name of the pathname's name sequence, that means the name of the file or directory denoted by this abstract path name is returned. But I need all the file names present in that particular location.
String name = (String)(new File("E:/abc_RESPONSE/Response_").getName());
I am using the above code please help to implement this.
Try this..
public void listFiles(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
System.out.println(file.getName());
}
}
}
try this
String[] names = new File("E:/abc_RESPONSE/Response_").list();

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

Categories

Resources