How to load the file from the inputstream? - java

I have the following code:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("test.groovy");
I need to pass this resource to the method called parse which takes File as param, so doing so fails:
new GroovyShell().parse(new FileInputStream(in));
How I can convert FileInputStream to File in java?

You can actually use: GroovyShell#parse(Reader) method:
Script result = new GroovyShell().parse(new InputStreamReader(in));

use this :
try {
URL url = this.getClass().getClassLoader().getResource("test.groovy");
File file = new File(url.toURI());
new Shell().parse(file);
} catch(...){...}
if you know exact path to "test.groovy", do this:
new Shell().parse(new File("path/to/test.groovy"));

Related

Java: fail to get the absolute path of a file

Below is my project like:
projectName
-package
- Util.java
- Test.json
In Util.java, I need to read the content from Test.json file and parse it.
Thus I use:
File currentfile = new File("");//get the current path
String absJsonPath = currentfile.getAbsolutePath() + "/Test.json";
While it did not work when I use a main method to test it. The thing is that the /src/package is lost in the obtained file path and I just got the path of the project.
And, when I deploy the project to weblogic server, I got another new error, the obtained current path is like:
.../DefaultDomain/.
I just want the file path in the file system, which is not related to the server.
What can I do for this? Thanks!
Put your file in resources folder and get it as following:
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("Test.json").getFile());
To read the content you can use following:
StringBuilder result = new StringBuilder("");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
It's CanonicalPath() not Absolute. Check this out, let me know if it any helps.
Try this to get current path
String currentPath = System.getProperty("user.dir");
If you want to read a file in a specific package. You can use
File jsonFile = new File(getClass().getResource("/Test.json").getFile());

Access static files from src/main/resources in Java

In my SpringBoot project I would like to read an image file located in:
I tried:
URL url = getClass().getResource("android.png");
File f = new File(url.getPath());
and:
URL url = getClass().getResource("static/images/android.png");
File f = new File(url.getPath());
but the result is null.
EDIT: this worked
try {
File file = new ClassPathResource("static/images/android.png").getFile();
} catch (IOException e) {
}
If you are using Spring, then it's better to use the built-in ClassPathResource class to access files within your classpath.
You can try this
File file = new ClassPathResource("/images/android.png").getFile();
because we can access static folder from anywhere
you can use this.getClass().getResource("/static/images").getFile(); to get the folder location and then append with the file name to get the file location.
Example
String path=this.getClass().getResource("/static/images").getFile();
File File f = new File(path+"/​android.png");
Have you tried
ClassLoader.getSystemResourceAsStream("/static/images/android.png");

Getting exception while trying to get FileOutputStream

We are getting the following exception while trying to get FileOutputStream for a filename:
java.lang.Exception: /var/tmp (Is a directory)
Please suggest what can be the cause of the error.
Code snippet where exception occurs:
public static FileOutputStream getFileInternal()
{
String pFilename = "/usr/tmp/";
File f = new File(pFilename);
pFilename = f.getCanonicalPath();
FileOutputStream fo = null;
fo = new FileOutputStream(pFilename, true);
return fo;
}
"/usr/tmp/" is a directory.
FileOutputStream only writes into regular files, not directories.
You can try something like:
String pFilename = "/usr/tmp/output.txt";
// ...
You cannot create a FileOutputStream from a directory. Different from File, they only work with actual files.

Assigning a destination for properties file in a java program

Sorry if this seems like a newbie question and im sure its just a little thing i need to change but it seems like my program cannot locate the destination for a properties file i coded in.
here is my code
public String metrics() throws IOException {
String result = "";
Properties prop = new Properties();
String propFileName = "C:\\Users\\JChoi\\Desktop\\config.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
if (inputStream == null) {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String Metrics = prop.getProperty("Metrics");
result = Metrics;
System.out.println(result);
return result;
}
I get a nullpointerexception error everytime i run the code but however, when i put the properties file in the resources folder and edit the string name to...
String propFileName = "config.properties";
works fine...any suggestions?
EDIT:
String result = "";
Properties prop = new Properties();
String propFileName = "C:\\Users\\JChoi\\Desktop\\config.properties";
FileInputStream fileInputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(fileInputStream);
SOLVED!
String propFileName = "C:\\Users\\JChoi\\Desktop\\googlebatchfile\\config.properties";
BufferedInputStream inputStream;
FileInputStream fileInputStream = new FileInputStream(propFileName);
inputStream = new BufferedInputStream(fileInputStream);
If you know the full path to a file, then do not try to open it using a classpath search (which is what getResourceAsStream() does).
Instead open the file using an inputsteam that takes a path.
Here is some code:
FileInputStream inputStream = new FileInputStream(propFileName);
The following might be a better technique (I'm not sure with property loading):
BufferedInputStream inputStream;
FileInputStream fileInputStream = new FileInputStream(propFileName);
inputStream = new BufferedInputStream(fileInputStream);
You are attempting to load a file using a classpath-based input stream but specifying a filepath.
This:
getClass().getClassLoader().getResourceAsStream(propFileName);
Will attempt to search the classpath starting at the root (based on whatever the classloader considers the root).
If you want to load a file from outside the classpath, you probably just want to use something like a FileInputStream instead.

Error: `error - java.lang.IllegalArgumentException: URI is not hierarchical while getting a file from a classpath

I have a file contained within a directory in a classpath. It looks like this pl/shenlon/io/gui/appData/file.txt. Now, when I try to convert it to a File and read with this code:
File cityNamesFile = new File(ClassLoader.getSystemResource("pl/shenlon/io/gui/appData/list.txt").toURI());
Scanner cns = new Scanner(cityNamesFile);
I get the following:-
error - java.lang.IllegalArgumentException: URI is not hierarchical.
How can I fix this problem?
If your calling class is itself in the same package as the text file, just use :
InputStream is = getClass().getResourceAsStream("list.txt");
Scanner cns = new Scanner(is);
Replace
File cityNamesFile = new File(ClassLoader.getSystemResource("pl/shenlon/io/gui/appData/list.txt").toURI());
with
File cityNamesFile = new File(Thread.currentThread().getContextClassLoader().getResource("pl/shenlon/io/gui/appData/list.txt").getFile());

Categories

Resources