Moving a Directory to a higher Directory in Java? - java

I have a folder called "data". It's in a subdirectory of my system, lets say in "big folder." I want to move the data folder out to my home folder, or "user." So the data folder's path is user/big folder/data. How do I move it out?

You should play around with the following snippet (not tested):
File src = new File("user/big folder/data");
File dest = new File("user");
boolean success = src.renameTo(new File(dest, src.getName()));
if (!success) {
// Directory was not successfully moved
}

Related

How to read the files inside a directory when Only Relative path of directory is known

In my java application,
1. I have relative path of the directory (Directory and files in it are part of the build).
2.The directory contains multiple files.
3. I want to read the file names in the parent directory.
4. Files can change later and are many in number, So I do not know the names of the files and Do not want my code to change if more files are added or removed or renamed
Now as I do not know the names of the files before hand as they may change later (there are multiple files which can vary according to environment). I only know about the relative path of the parent directory of the files.
How do I read the files ?
You can get list of all files of that directory by file.getlistFiles() method of file class.
It returns an array of files.
Even you can define filter for your files, so it returns exactly files that you want.
try {
File f = new File("D:/Programming");
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File f, String name) {
// We want to find only .c files
return name.endsWith(".c");
}
};
// Note that this time we are using a File class as an array,
// instead of String
File[] files = f.listFiles(filter);
look at this example.
If you want to use relative path, You can use
System.getProperty("user.dir");
String relative Path =System.getProperty("user.dir");
it returns the folder that you put your app in it.
If your folder has some subfolders, you can simply use file.list();
it returns names of all files and folders of your directory .
String [] listOfMyFilesAndFolders =file.list();
you can add these names to your path to access another folders.
You can check your path is a file or is a folder by using
file.isDirectory();
for ( String path: listOfFilesAndFolders ) {
File file = new File(basePath+path);
if ( file.isDirectory() {
// it is a folder and you can use another for loop or recursion to navigate sub directories
} else {
// it is a file and you can do everyThing you want}}
I think that you can use recursion to walk in your sub directories use recursion to read more
I hope helps.
the question is badly asked and the text is misleading.
"I have relative path of the directory (Directory and files in it are part of the build)" means little and nothing, you have to clarify what you mean.
Assuming you get a relative directory (for example "/folder1/folder2") via command line parameter, you basically have 3 choices:
1) start the program with the directory in which the jar is located as the "current directory", so that it can be used as a working directory. This approach requires that when you launch your application via the java -jar myapp.jar command first you prepend a "cd" command to place yourself directly in the directory. The code will look like the #hamidreza75 solution but obviously you will not have the variable "D: / Programming" but directly the relative path of the directory in which to read the files.
launch script
#echo off
cd {jar-folder}
java -jar myapp.jar
java code:
package com.sample.stack;
import java.io.File;
import java.io.FilenameFilter;
public class FileRenamenter {
public static void main(String[] args) {
final String relativePath = "folder1/folder2";
File directory = new File(relativePath);
String[] list = directory.list(new FilenameFilter(){
public boolean accept(File dir, String name) {
// filter condition
return true;
}
});
// echo file list
for (String filePath : list) {
System.out.println(filePath);
}
}
}
2) pass the folder to be controlled via command line parameter, like this:
launch script
#echo off
java -jar {jar-folder}/myapp.jar {jar-folder}
java code (only the "directory" variable changes)
File directory = new File(args[0], relativePath); // note args[0]
3) programmatically find the folder in which the jar is running [very discouraged practice] and then concatenate the relative path:
java code (only the "directory" variable changes):
String jarFolder = ClassLoader.getSystemClassLoader().getResource(".").getPath();
File directory = new File(jarFolder, relativePath); // note jarFolder

Rename linked resource programmatically

I an new to Eclipse Plugin Development and I am trying to rename my linked file.
I have created a linked file in Eclipse as below:
IFile myLinkedFile = folder.getFile(originalFileName);
myLinkedFile.createLink(myabsolutePath, IResource.NONE, null);
This works like a charm.
However, now I would like to rename myLinkedFile without changing the name of the original File. Just like the behavior of pressing F2 or by the Rename from the context menu that appears on right clicking the liked file.
I am trying to achieve renaming using move()
originalFile.move(newPath, IResource.FORCE, null);
However it always throws
org.eclipse.core.internal.resources.ResourceException
...and complains about my newPath. Can someone tell me what is wrong in my approach and how do I do it right?
My original file is a text file located at C:/Temp/originalFile.txt. I would like to rename the file to newFile.txt in my workspace. The exception says invalid path. For the newPath I have specified as C:/Temp/newFile.txt
In the below example the original files is located in the resources folder of my project
Here I am creating a new folder called myTextFiles. This folder will contain the linked files.
After creating the linked files I am trying to rename the linked files.
IFolder folder = myCurrentProject.getFolder("myTextFiles");
folder.create(IResource.REPLACE, true, null);
IFile file = folder.getFile(absoluteLocation); //absolute location of folder containing images
file.createLink(absoluteLocation, IResource.REPLACE, null);
folder.refreshLocal(IResource.DEPTH_INFINITE, null);
String myNewFileName = "newFile.txt";
IFile myLinkedFile = folder.getFile(myNewFileName);
IPath newPath = new Path(myNewFileName);
IFile movedFile = folder.getFile(newFileName);
movedFile.createLink(newPath, IResource.NONE, null);
folder.refreshLocal(IResource.DEPTH_INFINITE, null);
You can only use move to move the resource to a new location in the Eclipse workspace.
The path you specify for move must be a path relative to the root of the Eclipse workspace or relative to the current resource location - often just a file name.
So
IPath newPath = new Path("/project/folder/newFile.txt");
or
IPath newPath = new Path("newFile.txt");
Paths starting with '/' are relative to the workspace root (known as a 'absolute' path), anything else is relative to the current resource folder.
Paths in the Eclipse workspace never use "C:/"

java create file in specific folder

I am trying to create a temp file in a specific folder
In the image below, you can find the structure tree of my project. I am currently in FileAnalyse.java and trying to create the file in data, under webcontent.
The following tries did not work for me:
File dir = new File(System.getProperty("user.dir")+"/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);
or
File dir = new File("/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);
File dir = new File("WebContent/data");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
File subjectFile = File.createTempFile("subjects", ".json",dir);
This worked for me
note:
Your Version:
File dir = new File("/WebContent/data"); //has a / before WebContent
Correct Version:
File dir = new File("WebContent/data"); // no / before WebContent
Edit:
You can check if your path is the correct one with your attempts (or if you're on the right track to get the correct) when you print out the Path you're currently working with:
File dir = new File("YOUR/ATTEMPT");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
that way you can check the absolute path, and you can look if the current attempted Pathstring is nearly correct
I solved the problem by changing the working directory of eclipse by going to run configurations->tomcat->change working directory

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

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