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
Related
When I use relative path, I can run my Java program from Eclipse. But when I run it as a JAR file, the path doesn't work anymore. In my src/components/SettingsWindow.java I have:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/files/profile.ser"));
I get a FileNotFoundException.
My file directory looks like this:
file directory
What I've tried:
String filePath = this.getClass().getResource("/files/profile.ser").toString();
String filePath = this.getClass().getResource("/files/profile.ser").getPath();
String filePath = this.getClass().getResource("/files/profile.ser").getFile().toString();
And I'd just put filePath in new FileInputStream(filePath) but none of these work and I still get a FileNotFoundException. When I System.out.println(filePath) it says: files/profile.ser
I'm trying to get the path of src/files/profile.ser while I'm in src/components/SettingsWindow.java
You can get the URL to the class:
String path =
String.join("/", getClass().getName().split(Pattern.quote(".")))
+ ".class";
URL url = getClass().getResource("/" + path);
which will either yield "file:/path/to/package/class.class" or "jar:/path/to/jar.jar!/package/class.class". You either can work with the URL or use
JarFile jar =
((JarURLConnection) url.openConnection()).getJarFile();
and use jar.getName() to get the path to parse to get your installation directory.
To get the current JAR file path I use:
public static String getJarFilePath() throws FileNotFoundException {
String path = getClass().getResource(getClass().getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n"+path);
}
if(path.lastIndexOf("!")!=-1) path = path.substring(path.lastIndexOf("!/")+2, path.length());
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return path.substring(0, path.lastIndexOf('!')).replaceAll("%20", " ");
}
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\
I have a bit problem, and i dont seem to understand what is causing it.
i have a folder in my project, and in that folder i have a class, and i have a resource file (in this case jasper report).
but the only way i can access file is with absolute path or some path that starts from root of my project.
String path = "src/main/java/Views/LagerMain/lager.jrxml";
^^this works, both my class LagerController and lager.jrxml are under LagerMain folder, but when i try to do this :
String path = "lager.jrxml";
i have an error that file is not found.
I tried googling this to have a better understanding but i found nothing.
Bottom line, why cant i access my file, from class when they are both on same place, why does not relative path work.
If the main class is in a different directory, then the program will try to accesslager.jrxml there instead of the directory of the regular class.
For regular-class directory:
String path = new String(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.getPath() + System.getProperty("line.separator") + "lager.jrxml");
If that doesn't work, try this:
// your directory
File f = new File("src");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("lager") && name.endsWith("jrxml");
}
});
If you have more than one file with the name lager.jrxml, then this method will return both of them and you will need to use a for to cycle through them. Otherwise, you can just use
String path = new String(matchingFiles[0].getAbsolutePath())
For main-class directory:
String path = new String(System.getProperty("user.dir")
+ System.getProperty("line.separator") + "lager.jrxml");
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
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);