Copying files from one directory to another in java throws NoSuchFileException - java

I have a HashSet of Strings, which are names of files that I want to copy from the working direcorory to the "path" directory. I find that the following piece of code should be working, however, I get a java.nio.file.NoSuchFileException: /commits/1/hello.txt exception.
Hashset<String> stagedQueue = HashSet<String>();
stagedQueue.put("hello.txt");
stagedQueue.put("bye.txt");
String path = "/commits/" + commitID;
for (String file : stagedQueue) {
Files.copy((new File(file).toPath()),
(new File(path + "/" + file).toPath()));
What can I do to fix this? I can't figure out why I am getting these exceptions. Please note that I am moving these into an empty directory.

Don't go through File; you use java.nio.file.
Your problem here is that you try and copy your initial file into a directory which does not exist yet:
String path = "/commits/" + commitID;
First of all, this is the destination directory, so call it dstdir, for instance. Then create the base directory and copy the files into it:
final Path basedir = Paths.get("/commits", commitId);
Files.createDirectories(basedir);
for (final String file: baseQueue)
Files.copy(Paths.get(file), basedir.resolve(file));

Related

Java getting absolute path from directory count list

Expected:
find the number files in the folder, and collect the absolute path for each file in the directory.
File certificatePath = new File("resources/NPL");
String absolutePath = certificatePath.getAbsolutePath();
File directory = new File(absolutePath);
int fileCount=directory.list().length;
From the above code getting the no of files in folder (resources/NPL), now i'm struggle to get the absolute path for the files.
You should use listFiles instead fo list() (provided you have the security rights to do so), otherwise you are stuck with the file names.
Well first of all what does it mean to collect it? If you need the file names it is already there for you in an array of String[] which you get from directory.list() method. If you want the full names you can use listFiles() method which returns a File[] and each file has getAbsolutePath() method. Something like:
for (File file : directory.listFiles()) {
System.out.println(file.getAbsolutePath());
}

Java: Accessing a file that is in the same directory as .jar

I have a program that uses a file named list.txt to populate an ArrayList with its contents and then get a random line.
Here's the part that loads the file:
public class ReadList {
private Scanner f;
public void openFile(){
try{
f = new Scanner(new File("list.txt"));
}catch(Exception e){
System.out.println("File not found!");
}
}
However, it doesn't work when running it from a .jar file. I put the txt in the same directory and used f = new Scanner(new File("./list.txt")); yet it didn't work. I also tried some stuff I have found online but all I could manage to do is a) get a full path of the .jar with .jar included(/home/user/java/program.jar), and b) get a full path of the directory but without the / at the end(/home/user/java), which is a problem since I want this program to work on both Windows and Linux, therefore I can't simply do ("/home/user/java" + "/list.txt"), since Windows uses backslashes in paths.
So what's the simple way to just target the specific file(which will always be called list.txt) no matter which directory the file's in, as long as it's in the same place as the .jar?
Use this:
String filePath = System.getProperty("user.dir") + File.separator + "file.txt";
filePath will now contain the full path of file.txt which will be in the same dir as your jar.

Use Relative path in place of absolute path

First of all i request people do not consider it as a duplicate question, please look into query.
I am copying the xml files from one folder to other folder, in the source folder, i have some files which have some content like "backingFile="$IDP_ROOT/metadata/iPAU-SP-metadata.xml" but while writing to the destination folder.
i am replacing the "$IDP_ROOT" with my current working directory. The entire copying of files is for deploying into tomcat
server. The copying is done only when server starts for the first time.
Problem: If i change the folder name from my root path in my machine after i run the server,
the entire process will be stopped because the destination folder files already contains the content which is with
existed files names or folder names.
So i want to change it to relative path instead absolute path. What is the best way to do it?
Please look at code below:
// Getting the current working directory
String currentdir = new File(".").getAbsoluteFile().getParent() + File.separator;
if(currentdir.indexOf("ControlPanel")!=-1){
rootPath=currentdir.substring(0, currentdir.indexOf("ControlPanel"));
}else{
rootPath=currentdir;
}
rootPath = rootPath.replace("\\", "/");
// target file in source folder is having "backingFile="$IDP_ROOT/metadata/iPAU-SP-metadata.xml"
String content = FileReaderUtil.readFile(targetFile,
rootPath + "Idp/conf");
content = updatePath(content, Install.rootPath
+ "IdP/IdPserver/metadata","$IDP_ROOT");
FileWriterUtil.writeToFile(Install.rootPath
+ "IdP/IdPserver/idp/conf", content,
targetFile);
// update method
public String updatePath(String content, String replaceString,String replaceKey) {
replaceKey = replaceKey!=null ? replaceKey : "$IDP_SERVER_ROOT";
replaceString= replaceString.replace("\\","/");
String updateContent = content.replace(replaceKey,
replaceString);
return updateContent;
}

relative file path not working in Java

After reading that is it possible to create a relative filepath name using "../" I tried it out.
I have a relative path for a file set like this:
String dir = ".." + File.separator + "web" + File.separator + "main";
But when I try setting the file with the code below, I get a FileNotFoundException.
File nFile= new File(dir + File.separator + "new.txt");
Why is this?
nFile prints: "C:\dev\app\build\..\web\main"
and
("") file prints "C:\dev\app\build"
According to your outputs, after you enter build you go up 1 time with .. back to app and expect web to be there (in the same level as build). Make sure that the directory C:\dev\app\web\main exists.
You could use exists() to check whether the directory dir exist, if not create it using mkdirs()
Sample code:
File parent = new File(dir);
if(! parent.exists()) {
parents.mkdirs();
}
File nFile = new File(parent, "new.txt");
Note that it is possible that the file denoted by parent may already exist but is not a directory, in witch case it would not be possible to use it a s parent. The above code does not handle this case.
Why wont you take the Env-Varable "user.dir"?
It returns you the path, in which the application was started from.
System.getProperty(user.dir)+File.separator+"main"+File.separator+[and so on]

Find Path During Runtime To Delete File

The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.
Depending on what file you want to delete, and where it is stored, chances are that you are expecting Java to magically find the file.
String catName = 'test'
File file = new File(catName + '.txt');
If the program is running in say C:\TestProg\, then the File object is pointing to a file in the location C:\TestProg\test.txt. Since the file object is more of just a helper, it has no issues with pointing to a non-existent file (File can be used to create new files).
If you are trying to delete a file that is in a specific location, then you need to prepend the folder name to the file path, either canonically, or relative to the execution location.
String catName = 'test'
File file = new File('myfiles\\'+ catName +'.txt');
Now file is looking in C:\TestProg\myfiles\test.txt.
If you want to find that file anywhere, then you need a recursive search algorithm, that will traverse the filesystem.
The piece of code that you provided could be compacted to this:
boolean success = new File(catName + ".txt").delete();
The success variable will be true if the deletion was successful. If you do not provide the full absolute path (e.g. C:\Temp\test for the C:\Temp\test.txt file), your program will assume that the path is relative to its current working directory - typically the directory from where it was launched.
You should either provide an absolute path, or a path relative to the current directory. Your program will not try to find the file to delete anywhere else.

Categories