Try with Resource Java 7 - java

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.

Related

Filter all files in any depth by file prefix inside a directory

I'm using Apache Commons VFS2.0 to access files both in a local file system and a remote file system. I'm trying to find a way to filter all the descendent files in any depth with FileType=File and has a given filePrefix with the file name. I was able to do it for the same case except for file prefix, but for file extension, as follows.
FileSelector fileSelector = new FileExtensionSelector("extensions...");
directory.findFiles(fileSelector);
In this way, I was able to fetch all the files(no folders) in any depth with the given extension. I have tried the below approach but it only works for matching files with depth=1.
FileFilterSelector prefixFileSelector = new FileFilterSelector(new PrefixFileFilter("Prefix"));
directory.findFiles(prefixFileSelector);
Appreciate if anyone can give a suggestion.
new FileFilterSelector(fileFilter) {
#Override
public boolean traverseDescendents(FileSelectInfo fileInfo) {
return true;
}
#Override
public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
return accept(fileInfo);
}
}

Get file path of working directory

Im writing an annotation processor for android projects. I want to get the absolute path of the androids resource folder (I know it's configureable through gradle, but I ignore this case for now).
My idea is to get the absolute path of an processed element:
#MyAnnotation public class Foo{ ... }
So in my AnnotationProcessor I want to get the path to Foo.java.
#Override public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class))
try {
ProcessorMessage.info(element, "Path: %s %s", getWorkingDir(), getExecutionPath());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
ProcessorMessage.error(element, "Error " + e.getMessage());
}
return false;
}
private String getExecutionPath() throws UnsupportedEncodingException {
String path = AnnotatedAdapterProcessor.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
return decodedPath;
}
private String getWorkingDir() {
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
return s;
}
However it gives me the following output:
Path: /Users/XXXXX/.gradle/daemon/1.12 /Users/XXXXX/.m2/repository/com/example/myprocessor/processor/0.1.2-SNAPSHOT/processor-0.1.2-SNAPSHOT.jar
Is there a way to get the path where Foo.java is located? (Just to get a startpoint from where I will continue to start searching for the resource folder)
I think those paths probably depend on your build environment and if you construct them by hand it's possible that they won't work on every machine or with every IDE.
This question might help: Annotation processor, get project path
If that doesn't work I think you are still on the right track there, but should try using the actual resources instead of classes loaded by for the processor, like this:
String path = Foo.class.getProtectionDomain().getCodeSource().getLocation().getPath();
I'm not sure if this all also applies in the context of processors, but in general this should give you the root output directory of the class file:
String path = Foo.class.getClassLoader().getResource(".").getFile();
If you know that the output directory for example is in your_project/target/classes, you could use that get to the source or resource directory.

Creating File & Directories not working properly

I am currently working on a method that will create files and directories. Bellow is the use case & problem explained.
1) When a user specifies a path e.g "/parent/sub folder/file.txt", the system should be able to create the directory along with the file.txt. (This one works)
2) When a user specifies a path e.g "/parent/sub-folder/" or "/parent/sub-folder", the system should be able to create all directories. (Does not work), Instead of it creating the "/sub-folder/" or /sub-folder" as a folder, it will create a file named "sub-folder".
Here is the code I have
Path path = Paths.get(rootDir+"test/hello/");
try {
Files.createDirectories(path.getParent());
if (!Files.isDirectory(path)) {
Files.createFile(path);
} else {
Files.createDirectory(path);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
You need to use createDirectories(Path) instead of createDirectory(path). As explained in the tutorial:
To create a directory several levels deep when one or more of the
parent directories might not yet exist, you can use the convenience
method, createDirectories(Path, FileAttribute). As with the
createDirectory(Path, FileAttribute) method, you can specify an
optional set of initial file attributes. The following code snippet
uses default attributes:
Files.createDirectories(Paths.get("foo/bar/test"));
The directories
are created, as needed, from the top down. In the foo/bar/test
example, if the foo directory does not exist, it is created. Next, the
bar directory is created, if needed, and, finally, the test directory
is created.
It is possible for this method to fail after creating some, but not
all, of the parent directories.
Not sure of which File API you are using. But find below the simplest code to create file along with folders using java.io package.
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) {
FileTest fileTest = new FileTest();
fileTest.createFile("C:"+File.separator+"folder"+File.separator+"file.txt");
}
public void createFile(String rootDir) {
String filePath = rootDir;
try {
if(rootDir.contains(File.separator)){
filePath = rootDir.substring(0, rootDir.lastIndexOf(File.separator));
}
File file = new File(filePath);
if(!file.exists()) {
System.out.println(file.mkdirs());
file = new File(rootDir);
System.out.println(file.createNewFile());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

Xtend how to get full path of current working directory

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

How to get getclass().getResource() from a static context?

I have a function where I am trying to load a file to a URL object, because the example project said so.
public class SecureFTP {
public static void main(String[] args) throws IOException , ClassNotFoundException, SQLException , JSchException, SftpException{
File file = new File("/home/xxxxx/.ssh/authorized_keys");
URL keyFileURL = this.getClass().getClassLoader().getResource(file);
I tried using SecureFTP.class.getResource, but it still could not compile it.
I am fairly new to Java, so I know I am doing something wrong.
The main method is a static method, so trying to access this (= the current Object) will not work.
You can replace that line by
URL keyFileURL = SecureFTP.class.getClassLoader().getResource("/home/xxxxx/.ssh/authorized_keys");
From: How to call getClass() from a static method in Java?
Just use TheClassName.class instead of getClass().
Old question but this hasn't been said yet. You can do this from a static context:
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
classLoader.getResource("filename");
It can't compile because getResource takes a resource name (a String, and not a File) as parameter, in order to load a resource using the class loading mechanism (from the classpath). Using it with a File makes no sense. If you want to open a file, just use a FileInputStream or a FileReader.
See http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29, and include the compiler error message next time you have such a question.
SecureFTP.class.getClassLoader().getResource(<<your resource name>>);
Should do the trick!
Do it this way so that it works EITHER from a static method or an instance method:
public static String loadTestFile(String fileName) {
File file = FileUtils.getFile("src", "test", "resources", fileName);
try {
return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("Error loading test file: " + fileName, e);
return StringUtils.EMPTY;
}
}

Categories