Please consider the following code:
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
public static void main(String[] args) {
String filename = "c:/manyOthers/dir1/dir2/dir3";
File f = new File(filename);
String absPathS = f.getAbsolutePath();
System.out.println(absPathS);
// now I try to add a timestamp between dir1 and dir2/dir3 in abstPathS
Path absPath = Paths.get(absPathS);
int n = absPath.getNameCount();
String timestamp = "20210308";
Path subpath = absPath.subpath(0, n-2);
Path outPath = Paths.get(subpath.toString(), timestamp, absPath.subpath(n-2, n).toString());
System.out.println("Timestamped: " + outPath);
}
}
The output is:
c:\manyOthers\dir1\dir2\dir3
Timestamped: manyOthers\dir1\20210308\dir2\dir3
Basically - in my actual code - I receive the absolute path to a folder and I need to insert a subfolder whose name corresponds to a timestamp. The code above is just an example, I am using it here for providing a simple running example; in the actual code the path contains many more subfolders c:/folder1/folder2/.../dir1/dir2/dir3, so, please, if you intend to answer this question, do not tailor the solution to the specific code above.
In the code above, I have the absolute path C:/manyOthers/dir1/dir2/dir3/ and I need to insert a timestamp between dir1 and dir2/dir3. However, as you can see, the problem is that the final output has lost the drive letter.
I have read elsewhere that in Java there are no ways to add back that c:/, but it would be weird ince the prefix c:\ is returned by functions as File.getAbsolutePath(). For example:
File f = new File("any");
System.out.println(f.getAbsolutePath());
prints:
C:\Users\user\workspace\project\any
How I can keep / re-insert the drive letter in my paths?
The problem is that Path.subPath always returns a relative path.
But fortunately your Path absPath is absolute and contains C:\ as the root. So you can get that via absPath.getRoot().
Having this you can create Path outPath from that root:
...
Path outPath = Paths.get(absPath.getRoot().toString(), subpath.toString(), timestamp, absPath.subpath(n-2, n).toString());
...
As #user15244370 commented, the whole thing could be done much more elegant using Path.resolve without using Paths and Path.toString.
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
public static void main(String[] args) {
String filename = "c:/manyOthers/dir1/dir2/dir3";
Path absPath = Paths.get(filename);
System.out.println("Source path: " + absPath);
int n = absPath.getNameCount();
String timestamp = "20210308";
Path subpath = absPath.subpath(0, n-2);
Path outPath = absPath.getRoot().resolve(subpath).resolve(timestamp).resolve(absPath.subpath(n-2, n));
System.out.println("Timestamped: " + outPath);
}
}
Related
I want to get path after given token "html" which is a fix token and file path is below
String token = "html"
Path path = D:\data\test\html\css\Core.css
Expected Output : css\Core.css
below is input folder for the program. and defined as the constant in the code.
public static final String INPUT_DIR = "D:\data\test\html"
which will contains input html, css, js files. and want to copy these files to different location E:\data\test\html\ here so just need to extract sub path after html from the input file path to append it to the output path.
lets say input file are
D:\data\test\html\css\Core.css
D:\data\test\html\css\Core.html
D:\data\test\html\css\Core.js
so want to extract css\Core.css, css\Core.html, css\Core.js to append it to the destination path E:\data\test\html\ to copy it.
Tried below
String [] array = path.tostring().split("html");
String subpath = array[1];
Output : \css\Core.css
which is not expected output expected output is css\Core.css
Also above code is not working for below path
Path path = D:\data\test\html\bla\bla\html\css\Core.css;
String [] array = path.toString().split("html");
String subpath = array[1];
In this case I am getting something like \bla\bla\ which is not
expected.
If you only need the path in the form of a string another solution would be to use this code:
String path = "D:\\data\\test\\html\\css\\Core.css";
String keyword = "\\html";
System.out.println(path.substring(path.lastIndexOf(keyword) + keyword.length()).trim());
You can replace the path with file.getAbsolutePath() as mentioned above.
import java.io.File;
public class Main {
public static void main(String[] args) {
// Create a File object for the directory that you want to start from
File directory = new File("/path/to/starting/directory");
// Get a list of all files and directories in the directory
File[] files = directory.listFiles();
// Iterate through the list of files and directories
for (File file : files) {
// Check if the file is a directory
if (file.isDirectory()) {
// If it's a directory, recursively search for the file
findFile(file, "target-file.txt");
} else {
// If it's a file, check if it's the target file
if (file.getName().equals("target-file.txt")) {
// If it's the target file, print the file path
System.out.println(file.getAbsolutePath());
}
}
}
}
public static void findFile(File directory, String targetFileName) {
// Get a list of all files and directories in the directory
File[] files = directory.listFiles();
// Iterate through the list of files and directories
for (File file : files) {
// Check if the file is a directory
if (file.isDirectory()) {
// If it's a directory, recursively search for the file
findFile(file, targetFileName);
} else {
// If it's a file, check if it's the target file
if (file.getName().equals(targetFileName)) {
// If it's the target file, print the file path
System.out.println(file.getAbsolutePath());
}
}
}
}
}
This code uses a recursive function to search through all subdirectories of the starting directory and print the file path of the target file (in this case, "target-file.txt") if it is found.
You can modify this code to suit your specific needs, such as changing the starting directory or target file name. You can also modify the code to perform different actions on the target file, such as reading its contents or copying it to another location.
Your question lacks details.
Is the "path" a Path or a String?
How do you determine which part of the "path" you want?
Do you know the entire structure of the "path" or do you just have the delimiting part, for example the html?
Here are six different ways (without iterating, as you stated in your comment). The first two use methods of java.nio.file.Path. The next two use methods of java.lang.String. The last two use regular expressions. Note that there are probably also other ways.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathTest {
public static void main(String[] args) {
// D:\data\test\html\css\Core.css
Path path = Paths.get("D:", "data", "test", "html", "css", "Core.css");
System.out.println("Path: " + path);
Path afterHtml = Paths.get("D:", "data", "test", "html").relativize(path);
System.out.println("After 'html': " + afterHtml);
System.out.println("subpath(3): " + path.subpath(3, path.getNameCount()));
String str = path.toString();
System.out.println("replace: " + str.replace("D:\\data\\test\\html\\", ""));
System.out.println("substring: " + str.substring(str.indexOf("html") + 5));
System.out.println("split: " + str.split("\\\\html\\\\")[1]);
Pattern pattern = Pattern.compile("\\\\html\\\\(.*$)");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("regex: " + matcher.group(1));
}
}
}
Running the above code produces the following output:
Path: D:\data\test\html\css\Core.css
After 'html': css\Core.css
subpath(3): css\Core.css
replace: css\Core.css
substring: css\Core.css
split: css\Core.css
regex: css\Core.css
I assume you know how to modify the above in order to
I want to get file path after /test
I am trying to scan the "loremIpsum.txt" file to a String using the split method of the class String to store each word in a different position of an array, and last use a HashSet to find if there is any word repetition in the text.
But Eclipse doesn't recognize the file even though it is in the same package. I was wondering if there is something wrong with my code?
package Lab5;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Lorem {
public static void main(String[] args) {
String[] loremIpsum = null;
try {
loremIpsum = new Scanner(new File("loremIpsum.txt")).next().split(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(loremIpsum.length);
HashSet h = new HashSet();
for(int i=0;i<loremIpsum.length;i++) {
String word=loremIpsum[i];
System.out.println(word);
if(h.contains(word)) {
System.out.println("we found a duplicate");
} else {
h.add(word);
}
}
}
}
Error message and proof "lorem.txt" is in the same package:
The file will be looked for in the project directory (where bin and src folders are located). Move the file there.
You need to pass the parameter as a path.
try this
String path = new File("").getAbsolutePath();
path.concat("/loremIpsum.txt");
loremIpsum = new Scanner(new File(path)).next().split(" ");
basically youre just finding the current path and appending the file name youre wanting to read from.
Like the others said though, you can move it to your working directory as well.
Cheers!
When you call the File constructor with a relative path, it's relative to the working directory.
That usually won't be the same directory as the code calling the constructor. But that's okay, because if your file can be specified when you run the application, you don't want to presume that anyway.
You can specify the working directory in the Eclipse run configuration, on the Arguments tab.
You can see how a relative path has been resolved using the File method getAbsolutePath().
try {
File myFile = new File("loremIpsum.txt");
System.out.println("Absolute path = " + myFile.getAbsolutePath() );
loremIpsum = new Scanner(myFile).next().split(" ");
...
Is there a way to access the file inside archive while ignoring file name case using TrueZip?
Imagine following zip archive with content:
MyZip.zip
-> myFolder/tExtFile.txt
-> anotherFolder/TextFiles/file.txt
-> myFile.txt
-> anotherFile.txt
-> OneMOREfile.txt
This is how it works:
TPath tPath = new TPath("MyZip.zip\\myFolder\\tExtFile.txt");
System.out.println(tPath.toFile().getName()); //prints tExtFile.txt
How to do the same but ignore all case, like this:
// note "myFolder" changed to "myfolder" and "tExtFile" to "textfile"
TPath tPath = new TPath("MyZip.zip\\myfolder\\textfile.txt");
System.out.println(tPath.toFile().getName()); // should print tExtFile.txt
Code above throws FsEntryNotFoundException ... (no such entry)
It works for regular java.io.File, not sure why not for TFile of TrueZip or I am missing something?
My goal is to access each file just using only lowercase for files and folders.
Edit: 24-03-2017
Let's say I would like to read bytes from file inside mentioned zip archive MyZip.zip
Path tPath = new TPath("...MyZip.zip\\myFolder\\tExtFile.txt");
byte[] bytes = Files.readAllBytes(tPath); //returns bytes of the file
This snippet above works, but this one below does not (throws mentioned -> FsEntryNotFoundException). It is the same path and file just in lowercase.
Path tPath = new TPath("...myzip.zip\\myfolder\\textfile.txt");
byte[] bytes = Files.readAllBytes(tPath);
You said:
My goal is to access each file just using only lowercase for files and folders.
But wishful thinking will not get you very far here. As a matter of fact, most file systems (except Windows types) are case-sensitive, i.e. in them it makes a big difference if you use upper- or lower-case characters. There you can even have the "same" file name in different case multiple times in the same directory. I.e. it actually makes a difference if the name is file.txt, File.txt or file.TXT. Windows is really an exception here, but TrueZIP does not emulate a Windows file system but a general archive file system which works for ZIP, TAR etc. on all platforms. Thus, you do not have a choice whether you use upper- or lower-case characters, but you have to use them exactly as stored in the ZIP archive.
Update: Just as a little proof, I logged into a remote Linux box with an extfs file system and did this:
~$ mkdir test
~$ cd test
~/test$ touch file.txt
~/test$ touch File.txt
~/test$ touch File.TXT
~/test$ ls -l
total 0
-rw-r--r-- 1 group user 0 Mar 25 00:14 File.TXT
-rw-r--r-- 1 group user 0 Mar 25 00:14 File.txt
-rw-r--r-- 1 group user 0 Mar 25 00:14 file.txt
As you can clearly see, there are three distinct files, not just one.
And what happens if you zip those three files into an archive?
~/test$ zip ../files.zip *
adding: File.TXT (stored 0%)
adding: File.txt (stored 0%)
adding: file.txt (stored 0%)
Three files added. But are they still distince files in the archive or just stored under one name?
~/test$ unzip -l ../files.zip
Archive: ../files.zip
Length Date Time Name
--------- ---------- ----- ----
0 2017-03-25 00:14 File.TXT
0 2017-03-25 00:14 File.txt
0 2017-03-25 00:14 file.txt
--------- -------
0 3 files
"3 files", it says - quod erat demonstrandum.
As you can see, Windows is not the whole world. But if you copy that archive to a Windows box and unzip it there, it will only write one file to a disk with NTFS or FAT file system - which one is a matter of luck. Very bad if the three files have different contents.
Update 2: Okay, there is no solution within TrueZIP for the reasons explained in detail above, but if you want to work around it, you can do it manually like this:
package de.scrum_master.app;
import de.schlichtherle.truezip.nio.file.TPath;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
public class Application {
public static void main(String[] args) throws IOException, URISyntaxException {
TPathHelper tPathHelper = new TPathHelper(
new TPath(
"../../../downloads/powershellarsenal-master.zip/" +
"PowerShellArsenal-master\\LIB/CAPSTONE\\LIB\\X64\\LIBCAPSTONE.DLL"
)
);
TPath caseSensitivePath = tPathHelper.getCaseSensitivePath();
System.out.printf("Original path: %s%n", tPathHelper.getOriginalPath());
System.out.printf("Case-sensitive path: %s%n", caseSensitivePath);
System.out.printf("File size: %,d bytes%n", Files.readAllBytes(caseSensitivePath).length);
}
}
package de.scrum_master.app;
import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.nio.file.TPath;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
public class TPathHelper {
private final TPath originalPath;
private TPath caseSensitivePath;
public TPathHelper(TPath tPath) {
originalPath = tPath;
}
public TPath getOriginalPath() {
return originalPath;
}
public TPath getCaseSensitivePath() throws IOException, URISyntaxException {
if (caseSensitivePath != null)
return caseSensitivePath;
final TPath absolutePath = new TPath(originalPath.toFile().getCanonicalPath());
TPath matchingPath = absolutePath.getRoot();
for (Path subPath : absolutePath) {
boolean matchFound = false;
for (TFile candidateFile : matchingPath.toFile().listFiles()) {
if (candidateFile.getName().equalsIgnoreCase(subPath.toString())) {
matchFound = true;
matchingPath = new TPath(matchingPath.toString(), candidateFile.getName());
break;
}
}
if (!matchFound)
throw new IOException("element '" + subPath + "' not found in '" + matchingPath + "'");
}
caseSensitivePath = matchingPath;
return caseSensitivePath;
}
}
Of course, this is a little ugly and will just get you the first matching path if there are multiple case-insensitive matches in an archive. The algorithm will stop searching after the first match in each subdirectory. I am not particularly proud of this solution, but it was a nice exercise and you seem to insist that you want to do it this way. I just hope you are never confronted with a UNIX-style ZIP archive created on a case-sensitive file system and containing multiple possible matches.
BTW, the console log for my sample file looks like this:
Original path: ..\..\..\downloads\powershellarsenal-master.zip\PowerShellArsenal-master\LIB\CAPSTONE\LIB\X64\LIBCAPSTONE.DLL
Case-sensitive path: C:\Users\Alexander\Downloads\PowerShellArsenal-master.zip\PowerShellArsenal-master\Lib\Capstone\lib\x64\libcapstone.dll
File size: 3.629.294 bytes
I dont have TrueZip installed but I was also wondering how it would work in normal Path, so I implemented below way quite similar #kriegaex solution, you can try using caseCheck(path):
public class Main {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
Path path = Paths.get("/home/user/workspace/JParser/myfolder/yourfolder/Hisfolder/a.txt");
Instant start = Instant.now();
Path resolution;
try{
resolution = caseCheck(path);
}catch (Exception e) {
throw new IllegalArgumentException("Couldnt access given path", e);
}
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("Path is: " + resolution + " process took " + duration.toMillis() + "ms");
}
/**
* #param path
* #return
* #throws IOException
*/
private static Path caseCheck(Path path) throws IOException {
Path entryPoint = path.isAbsolute() ? path.getRoot() : Paths.get(".");
AtomicInteger counter = new AtomicInteger(0);
while (counter.get() < path.getNameCount()) {
entryPoint = Files
.walk(entryPoint, 1)
.filter(s -> checkPath(s, path, counter.get()))
.findFirst()
.orElseThrow(()->new IllegalArgumentException("No folder found"));
counter.getAndIncrement();
}
return entryPoint;
}
/**
* #param s
* #param path
* #param index
* #return
*/
private static final boolean checkPath(Path s, Path path, int index){
if (s.getFileName() == null) {
return false;
}
return s.getFileName().toString().equalsIgnoreCase(path.getName(index).toString());
}
}
I wrote a file writing script that lets you write in a file you are looking for in the console, then when you press enter it tries to find the file to see if it exists. My program works, but I don't like that I need the full pathname, every single time. I want a user to just be able to write, say, file_name.txt and the program searches a single directory for it.
Currently, I must use the full pathname every single time. This is not all of my code, but you can see that my file names have a hard coded String pathname. But what if someone else wants to run the program on their own computer? I tried looking for answers to this, but Java is always very difficult for me. If you know a way to make my code generic enough so my Scanner object can take just the file name, that would be so helpful. Thanks, let me know if anything is unclear. I have a Mac, but it should be able to work on any OS.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;
public class FileHandler {
public static boolean fileCheck = true;
public static File logFile;
public static PrintWriter logPrinter;
public static PrintWriter handMadeFile;
public static LocalDate date = LocalDate.now();
public static File fileFromScanner;
public static File directory = new File("/Users/mizu/homework");
public static String fileName;
public static File file;
public static String created = "Log has been created.";
public static String myLogFileName = "/Users/mizu/homework/my_log.txt";
public static String mainFileName = "/Users/mizu/homework/main_file.txt";
public static String fileFromMethod = "/Users/mizu//homework/file_from_method.txt";
public static String fileMessage = "I just wrote my own file contents.";
public static void main(String[] args) {
if (!directory.exists())
{
// create new directory called homework
directory.mkdir();
}
// gets file request from user
System.out.print("Enter file to find: ");
Scanner in = new Scanner(System.in);
String fileName = in.nextLine();
// initialize the main_file
fileFromScanner = new File(mainFileName);
// if main_file exists or not, print message to my_log
if (!fileFromScanner.exists())
{
// create my_log file (logFile), to keep track of events
writeToLog(created);
writeToLog("File path you entered: "
+ fileName + " does not exist.");
System.out.println(fileName + " - does not exist.");
// create file since it doesn't exist
File mainFile = new File(mainFileName);
try {
PrintWriter pwMain = new PrintWriter(new BufferedWriter
(new FileWriter(mainFile)));
writeToLog("Created " + mainFileName);
pwMain.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
writeToLog(fileName + " already exists.");
System.out.println(fileName + " - already exists.");
}
// use writeToFile method to write file, create new file name
FileHandler testFile = new FileHandler(fileFromMethod);
testFile.writeToFile(testFile, fileMessage);
} // end Main
All of the other methods are below here, but not shown to keep it short.
As stated in the comments, there are several tools already available to search files in a directory. However, to answer your question, I wrote a simple program that should do what you are looking for:
public static void main(String[] args) {
// Get the absolute path from where your application has initialized
File workingDirectory = new File(System.getProperty("user.dir"));
// Get user input
String query = new Scanner(System.in).next();
// Perform a search in the working directory
List<File> files = search(workingDirectory, query);
// Check if there are no matching files
if (files.isEmpty()) {
System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
+ query + "'");
return;
}
// print all the files that matched the query
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}
public static List<File> search(File file, String query) {
List<File> fileList = new ArrayList<File>();
// Get all the files in this directory
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
// use recursion to search in all directories for the file
fileList.addAll(search(f, query));
} else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
// if the filename matches the query, add it to the list
fileList.add(f);
}
}
}
return fileList;
}
1- You can make users set an environment variable to your path and use the path name in your code.
2- You can check the operating system, and put your files in a well-known folder. (C: for windows, /home for Ubuntu, /WhateverMacFolder for mac and if it is some other os ask user to enter the path.
3- You can create a folder in default path of your program and use it.
I was hoping someone could explain why this will not work and what my solution might be.
I have tried the following to learn what happens:
String s = "\\users\\udc8\\a4471\\My Documents\\MATLAB\\blockdiagram.xml";
String st = "\\";
String st2 = st + s;
System.out.println(st2);
Giving me the following output:
\\users\udc8\a4471\My Documents\MATLAB\blockdiagram.xml
Which is the correct path to the file.
Then I try to parse this file using SAX and I get an IOEXception saying the file does not exist. I have tried using File and getPath(),getCanonicalPath() and getAbsolutePath().
When running the parser i get the msg:
Due to an IOException, the parser could not check \\users\udc8\a4471\My Documents\MATLAB\\blockdiagram.xml
This is the code starting the parsing:
try {
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.parse(st2);
System.out.println(s + " is well-formed.");
}
catch (SAXException e) {
System.out.println(s + " is not well-formed.");
}
catch (IOException e) {
System.out.println(
"Due to an IOException, the parser could not check "
+ s
);
}
Running a similar program that does not have its own messege the following error messege is returned:
java.io.FileNotFoundException: \\users\udc8\a4471\workspace\SAX Intro\users\udc8\a4471\My Documents\MATLAB\blockdiagram.xml (The system cannot find the file specified)
The file has no special restrictions (as far as I can see), Nothing ticked in looking at file properties and I can manually re-write the content.
Any ideas?
Maybe it is just because of your path has two \-signs too much in it. I recomend you give it a try with your variable s instead of s2 that has the additional \-signs added.
To be honest i just realized how less i know about paths in java, expecially when it comes to different OS.
I however managed to get it to run on a Windows machine like so:
import java.io.File;
import java.io.IOException;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class SaXSample {
public static void main(String[] args) {
new SaXSample().run();
}
public void run() {
System.out.println("This class is located under: "+getAbsolutePath());
// using absolut pathd
String absolutPath = "D:\\temp\\Oki.xml";
File f = new File(absolutPath);
System.out.println("Does the file exist using the absolut path? -> "+f.exists());
runSaX(absolutPath);
// using relative path (i dont know why it knows which drive C:/, D:/ to take but my .class is running from the same drive as the .xml is in)
String relativePath = "\\temp\\Oki.xml";
File f2 = new File(relativePath);
System.out.println("Does the file exist using the relative path? -> "+f2.exists());
runSaX(relativePath);
// using a "wrong" relative path:
String wrongRelativePath = "\\\\temp\\Oki.xml";
File f3 = new File(wrongRelativePath);
System.out.println("File relative path: "+f3.getPath()+" , File absolut path: "+f3.getAbsolutePath());
runSaX(wrongRelativePath);
}
private void runSaX(String path) {
try {
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.parse(path);
System.out.println(path + " is well-formed.");
} catch (SAXException e) {
System.out.println(path + " is not well-formed.");
} catch (IOException e) {
System.out
.println("Due to an IOException, the parser could not check "
+ path);
}
}
private String getAbsolutePath() {
java.security.ProtectionDomain pd = SaXSample.class
.getProtectionDomain();
if (pd == null)
return null;
java.security.CodeSource cs = pd.getCodeSource();
if (cs == null)
return null;
java.net.URL url = cs.getLocation();
if (url == null)
return null;
java.io.File f = new File(url.getFile());
if (f == null)
return null;
return f.getAbsolutePath();
}
}
Which in my case leads to this output (sorry i dont know how to format console output):
This class is located under: D:\devjba\jba\bin
Does the file exist using the absolut path? -> true
D:\temp\Oki.xml is well-formed.
Does the file exist using the relative path? -> true
\temp\Oki.xml is well-formed.
File relative path: \\temp\Oki.xml , File absolut path: \\temp\Oki.xml
Due to an IOException, the parser could not check \\temp\Oki.xml
Since you implied in the comments that you wish to be able to select certain files or directorys i recomend you have a look at the JFileChooser. It is a simple way to let the user choose something that actually exists and will provide you the absolute path to the selected file/files.
NOTE: i have no clue why in the relative path-case the correct drive D:/ is used and not the other C:/