Use Relative path in place of absolute path - java

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

Related

Gradle project and resources folder and logical root for creating files

I have a problem understanding how Intellij is working with a Gradle project and the resources folder.
I have created a default Gradle project its created a module 'group', and a module when looking in the module group the src/main/resources folder shows as a 'resource folder' (however it doesn't in the stand-alone module, where groovy/java/resources are all grey).
So that sort out seems to work when compiling code generally.
I tried however to create a file in Groovy script like this
File newFile = new File ("resources/temp.txt")
def fpath = newFile.toURL()
if (!newFile.exists()) {
println "creating new $fpath file "
newFile.createNewFile()
}
However run you run this it fails at bit like this
creating new file:/D:/Intellij - Azure/quickstart-java/graph/src/main/groovy/playpen/resources/temp.txt file
Caught: java.io.IOException: The system cannot find the path specified
java.io.IOException: The system cannot find the path specified
at java_io_File$createNewFile$1.call(Unknown Source)
at playpen.TinkerPop-Example.run(TinkerPop-Example.groovy:47)
The File seems to have relative root .../src/main/groovy/playpen which is where my script is. there is no src/main/groovy/playpen/resources/ so it fails
if a use File("/resources/temp.txt") and look at the URL it shows asD:\resources\temp.txt` defaulting to same drive as where the script is defined.
If you remove the resources prefix - the file gets created in playpen - again assumed root is same as the source program script.
What I want is to read a file from the 'resources' folder but unless I go to absolute file paths it just ignores the 'resources' folder and only looks in the Groovy source folders.
So for example if I copy the temp.txt into the resources folder and run this
File newFile = new File ("temp.txt")
def fpath = newFile.toURL()
if (!newFile.exists()) {
println "creating new $fpath file "
newFile.createNewFile()
} else {
println "reading file at $fpath"
}
it just creates a new temp.txt in the playpen package where the script runs and doesn't see a copy from 'resources' folder.
So what format of 'file name' do I use so that the 'resources' folder is naturally used to resolve file names - without having to use absolute file names?
Equally if want to create a File programmatically and save that in the 'resources' folder where the script runs from src/main/groovy/playpen, what's the path name that puts it in the correct location.
I'm missing something basic here and can't figure out how to read/or write from the resources folder.
ended up with brute force and ignorance on this one - someone may have a 'smarter'answer, but this one appears to be working. Slightly tweaked some code i got working.
I'm using groovy here rather than java (just less boilerplate noise), and nice File groovy methods
steps -
(1)first locate root of your IDE/project using System.getProperty("user.dir")
(2) get the current resource file for 'this' - the class you run from ide
(3) see if the resource is in $root/out/test/.. dir - it so its a test else its your normal code.
(4) set resourcePath now to correct 'location' either in src/main/resources or src/test/resources/ - then build rest of file from this stub
(5) check if file exists - if so delete and rewrite this (you can make this cleverer)
(6) create file and fill its contents
job done this file should now appear where you expect it. Happy to take cleverer ways to get do this - but for anyone else stuck this seems to do the trick
void exportToFile (dir=null, fileName=null) {
boolean isTest = false
String root = System.getProperty("user.dir")
URL url = this.getClass().getResource("/")
File loc = new File(url.toURI())
String canPath = loc.getCanonicalPath()
String stem = "$root${File.separatorChar}out${File.separatorChar}test"
if (canPath.contains(stem))
isTest = true
String resourcesPath
if (isTest)
resourcesPath = "$root${File.separatorChar}src${File.separatorChar}test${File.separatorChar}resources"
else
resourcesPath = "$root${File.separatorChar}src${File.separatorChar}main${File.separatorChar}resources"
String procDir = dir ?: "some-dir-string"
if (procDir.endsWith("$File.separatorChar"))
procDir = procDir - "$File.separatorChar"
String procFileName = fileName ?: "somedefaultname"
String completeFileName
File exportFile = "$resourcesPath${File.separatorChar}$procDir${File.separatorChar}${procFileName}"
exportFile = new File(completeFileName)
println "path: $procDir, file:$procFileName, full: $completeFileName"
exportFile.with {
if (exists())
delete()
createNewFile()
text = toString()
}
}

Copying files from one directory to another in java throws NoSuchFileException

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

Unable to check if file exists or not in web project

I have a pdf file in my web project at the below location :
"static/Downloadables/20/Home_insurance_booklet.pdf "
"static" is present in the WebContent. The context root of the project is "pas".
In one of the jsp, I need to check if the file Home_insurance_booklet.pdf exists or not. I tried in many ways but unable to succeed. Below is the code I have used.
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
Through the file exists, the condition is returning false. How to check if the file exists or not w.r.t to certain location in the root of the web project ?
Edit:
File path displayed is
/pas/static/Downloadables/20/Home_insurance_booklet.pdf
Try the following:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
And here is the API-Doc of getRealPath():
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Use
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
The ServletContext#getRealPath() converts a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root.
After that append in this way :
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
Then use
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
check whether file is loaded in the project or not. and then try for absolute path first of the file in your code then try for relative path.
You have to use a file system based URL instead of relative web based URL.

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]

Specifying a relative path in File in Java

I'm uploading images using Spring and Hibernate. I'm saving images on the server as follows.
File savedFile = new File("E:/Project/SpringHibernet/MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);
Where itemName is the image file name after parsing the request (enctype="multipart/form-data"). I however need to mention the relative path in the constructor of File. Something like the one shown below.
File savedFile = new File("MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);
But it doesn't work throwing the FileNotFoundException. Is there a way to specify a relative path with File in Java?
Try printing the working directory from your program.
String curDir = System.getProperty("user.dir");
Gets you that directory. Then check if the directories MultiplexTicketBooking/web/images/ exist in that directory.
Can't count the number of times I've been mistaken about my current dir and spent some time looking for a file I wrote to...
It seems the server should offer functionality as might be seen in the methods getContextPath() or getRealPath(String). It would be common to build paths based on those types of server related and reproducible paths. Do not use something like user.dir which makes almost no sense in a server.
Update
ServletContext sc=request.getSession().getServletContext();
File savedFile = new File(sc.getRealPath("images")+"\\" + itemName);
Rather than use "\\" I'd tend to replace that with the following which will cause the correct file separator to be used for each platform. Retain cross-platform compatibility for when the client decides to swap the MS/ISS based server out for a Linux/Tomcat stack. ;)
File savedFile = new File(sc.getRealPath("images"), itemName); //note the ','
See File(String,String) for details.
You could get the path of your project using the following -
File file = new File("");
System.out.println("" + file.getAbsolutePath());
So you could have a constants or a properties file where you could define your path which is MultiplexTicketBooking/web/images/ after the relative path.
You could append your path with the path you get from file.getAbsolutePath() and that will be the real path of the file. - file.getAbsolutePath() + MultiplexTicketBooking/web/images/.
Make sure the folders after the Project path i.e. MultiplexTicketBooking/web/images/ exist.
You can specify the path both absolute and relative with File. The FileNotFoundException can be thrown because the folder might be there. Try using the mkdirs() method first in to create the folder structure you need in order to save your file where you're trying to save it.

Categories