I have written a grammar that allows the user to input a relative path. (e.g. "../../temp/out/path"
May aim is to get the absolute path based on the input from the user, and the absolute path of the current working directory so that I can also check if the input path is valid or not.
Is there libraries or built in functions that I can use to get the absolute path?
Something similar to C's _getcwd() function.
Yes, Java has a File class. You can create one by calling this constructor which takes a String. Then you can call getAbsolutePath() on it. You can call it like this:
package com.sandbox;
import java.io.File;
public class Sandbox {
public static void main(String[] args) {
File file = new File("relative path");
String absolutePathString = file.getAbsolutePath();
}
}
This will print a complete absolute path from where your application has initialized.
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +System.getProperty("user.dir"));
}
}
Related
I am trying to write my own function in Cup-carbon.
I followed the steps in the user-guide carefully, but an error appeared to tell me that the variable Function_Calc can't be found. The two codes I was added to the source-code are shown below.
I wrote the below code in this path.
(Path) Package Script_functions=> Class ScriptFunction=> method
function
if (function.equals("myf")){
return Function_Calc.myf(args);
}
I wrote the below code in this path.
(Path) Package Script_functions=> Class Functions
public static String myf (String [] args) throws Exception{
String valToReturn = "Nassser";
return valToReturn;
}
And I invoked the function as follows:
function x myf
But unfortunately, it didn't work.
I have a simple java program to test Try with resource in java , I am getting the File Not Found error, The Program and file are in the same package, Can somebody tell me what directory does File with resource start to search with
public class LoadConfigFile {
public static String getProperty(String propertyName) {
String propertyValue = null;
try (InputStream in = new FileInputStream("Properties.properties")) {
Properties prop = new Properties();
prop.load(in);
propertyValue = prop.getProperty(propertyName);
} catch (IOException e) {
System.out.println("Error Reading Property File" + e.getMessage().toString());
}
return propertyValue;
}
}
Properties.properties
properties.one=1
properties.two=2
properties.three=3
properties.four=4
properties.five=5
Main.java
public class Main {
public static void main(String[] args) {
String s = LoadConfigFile.getProperty("property.one");
System.out.println(s);
}
}
Working directory for process, to get that in Java you can use
System.out.println(System.getProperty("user.dir"));
If you have file within a Java package you should not access it as file but as resource:
InputStream in = this.getClass().getResourceAsStream("Properties.properties");
If you look at the source code for the FileInputStream constructor, you'll see that it, in turn, invokes File's constructor.
And if you have a look at the documentation for File, you will find a good explanation of how the path string is interpreted.
In particular, notice the following snippet:
A pathname, whether abstract or in string form, may be either absolute
or relative. An absolute pathname is complete in that no other
information is required in order to locate the file that it denotes. A
relative pathname, in contrast, must be interpreted in terms of
information taken from some other pathname. By default the classes in
the java.io package always resolve relative pathnames against the
current user directory. This directory is named by the system property
user.dir, and is typically the directory in which the Java virtual
machine was invoked.
I wanted to remove the spaces that Windows puts in filenames.
I ran the following code to rename all the files in a test directory thus. The result: all the files disappeared.
I am puzzled as to why.
import java.io.*;
public class FileRenamer {
public static void main(String[] args) {
for (File file: (new File("O:\\test0")).listFiles())
file.renameTo(new File(file.getName().replaceAll("\\s","")));
System.exit(0);
}
}
TL;DR: You are moving the file.
You list the files in a directory "O:\\test0.
For each such file you then create a String:
file.getName().replaceAll("\\s","")
You end up with:
new File("someFileName")
So you have called:
file.renameTo(new File("someFileName"))
Now, someFileName is not an absolute path; but a relative path. So you have moved from O:\\test0\\some File Name to someFileName, where someFileName is in the directory of the program.
P.S. there is no need to call System.exit(0).
Yes, I found the files had been moved to my class file directory.
Boris's tip about relative vs. absolute paths showed me the solution: to use the
public File(File parent, String child)
constructor for the new abstract File object. The following code did the job correctly.
import java.io.*;
public class FileRenamer {
public static void main(String[] args) {
File dir = new File("O:\\test0");
for (File file: dir.listFiles())
file.renameTo(new File(dir, file.getName().replaceAll("\\s","")));
}
}
I am using eclipse and I have my text file in the correct directory (src folder). I just want to read the file and count all the words in it. For some reason I am getting a file not found exception being thrown.
here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Tester {
public static int getSizeOfDictionary(File dictionary)
throws FileNotFoundException {
int count = 0;
Scanner reader = new Scanner(dictionary);
while (reader.hasNextLine()) {
reader.nextLine();
count++;
}
reader.close();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
File test = new File("words.txt");
System.out.println(getSizeOfDictionary(test));
}
}
You could use this.getClass().getResource("words.txt") which will find that file on the current classpath.
From the main method you could use: Tester.class.getResource("words.txt")
when eclipse launches jvm it sets current directory to project base directory generally (unless you modify the default current directory)
${workspace_loc}/project_name
so you need to change your File initialization to
File test = new File("src/words.txt");
Note:
It will just be limited to this project structure, if you export it to jar it will not work any more, I assume you just need it as part of exercise
You have to use property class to access your file within class-path and source folder
you can try like:
this.getClass().getResourceAsFile("words.txt")
Is there a (compatible, if possible) way to determine the absolute path of a loaded Class?
Of course, this is not always possible (if you think of dynamically created classes), but
if the loaded Class is inside a jar how to get the absolute path for this jar?
MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()
Fullcode:
package org.life.java.so.questions;
/**
*
* #author jigar
*/
public class GetClassPath {
public static void main(String[] args) {
System.out.println(GetClassPath.class.getProtectionDomain().getCodeSource().getLocation().getPath());
}
}
Output:
/C:/Documents%20and%20Settings/argus/My%20Documents/NetBeansProjects/temp/build/classes/
Or
ClassLoader loader = GetClassPath.class.getClassLoader();
System.out.println(loader.getResource("org/life/java/so/questions/GetClassPath.class"));
Try something like this:
SomeClass.class.getResource("/" + SomeClass.class.getName() + ".class").toString();
If the class is loaded from jar the result should be something like:
jar://myjar.jar!path/to/SomeClass.class