How to Autoit.exe file calling in java class - java

I want to call the Autoit.exe file in the java class. I kept the AutoIt.exe file inside the executable package and read it in UploadProfile.java class.
// Label: image
driver.findElement(By.id("uploadimage")).click();
//for 1mb file uploading
Runtime.getRuntime().exec("D:\\netxploretesting\\unifytreewebautomation\\src\\test\\java\\executables\\fileupload.exe"+" "+"E:\\images\\profile.JPG");
//assertion for message display
assertTrue(driver.findElement(By.xpath("//strong[contains(text(),\"You are exceeding the size limit, it can't be more\")]")).getText().matches("You are exceeding the size limit, it can't be more than 512 KB."));
System.out.println(driver.findElement(By.xpath("//strong[contains(text(),\"You are exceeding the size limit, it can't be more\")]")).getText());
i want to change "Runtime.getRuntime().exec("D:\netxploretesting\unifytreewebautomation\src\test\java\executables\fileupload.exe"+" "+"E:\images\profile.JPG");" this code because when i execute to other system that time i change the file path

You can distribute exe with your package and keep it in sources but it is actually a sort of bad practice. However if you have no options I can suggest the following way:
Put your exe file to resources folder
Within the code implement copying the file from resources to some place in the file system.
Execute that file from the code
Build jar (exe file will be placed as a resource to your jar)
Below is a simple example on how you can achieve points 2 and 3:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException, IOException {
// Copy file from resources to file system (path taken from the command line argument)
InputStream is = Main.class.getResourceAsStream("Autoit.exe");
File exeFile = new File(args[0]);
FileOutputStream fos = new FileOutputStream(exeFile);
byte bytes[] = new byte[1000];
int k = 0;
while((k = is.read(bytes)) != -1){
fos.write(bytes, 0, k);
}
fos.close(); // Do not forget to close the outputstream, otherwise your code will be holding the file and it won't be possible to execute it
// Below is just an example on how you can execute the file after copying
List<String> commands = new ArrayList<String>(); //
commands.add(args[0]); // Start file with argument
commands.add("E:\\images\\profile.JPG"); //
Process p = new ProcessBuilder().command(commands).start();
InputStream i = p.getInputStream(); //
Scanner scanner = new Scanner(i); //
while (scanner.hasNextLine()){ // Print the output of the file
System.out.println(scanner.nextLine()); //
} //
}
}
In this example we have our your_application.exe file in resource folder. We also take the destination for the file copying from command line arguments. So the way how to execute the jar will look like:
java -jar mysuper.jar c:/Folder_To_Store_Copy_Of_Autoit/Autoit.exe

if you want to run executable file as per system changes.
then save the executable file at project level.
and then call System.getPropert("user.dir") this will return your project path.
then add the package path which contains executable file. like below.
Runtime.getRuntime().exec(System.getProperty("user.dir")+"your package\file.exe")

Related

getResourceAsStream returning Null when reading file [duplicate]

I am trying to read a text file which is set in CLASSPATH system variable. Not a user variable.
I am trying to get input stream to the file as below:
Place the directory of file (D:\myDir) in CLASSPATH and try below:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
Place full path of file (D:\myDir\SomeTextFile.txt) in CLASSPATH and try the same above 3 lines of code.
But unfortunately NONE of them are working and I am always getting null into my InputStream in.
With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
If those aren't working, that suggests something else is wrong.
So for example, take this code:
package dummy;
import java.io.*;
public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
And this directory structure:
code
dummy
Test.class
txt
SomeTextFile.txt
And then (using the Unix path separator as I'm on a Linux box):
java -classpath code:txt dummy.Test
Results:
true
true
When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.
Resource resource = new ClassPathResource("com/example/Foo.class");
Through the Resource interface you can access the resource as InputStream, URL, URI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.
This is how I read all lines of a text file on my classpath, using Java 7 NIO:
...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
...
Files.readAllLines(
Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());
NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.
Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets
(these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").
Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8
Please try
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
Your tries didn't work because only the class loader for your classes is able to load from the classpath. You used the class loader for the java system itself.
To actually read the contents of the file, I like using Commons IO + Spring Core. Assuming Java 8:
try (InputStream stream = new ClassPathResource("package/resource").getInputStream()) {
IOUtils.toString(stream);
}
Alternatively:
InputStream stream = null;
try {
stream = new ClassPathResource("/log4j.xml").getInputStream();
IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
To get the class absolute path try this:
String url = this.getClass().getResource("").getPath();
Somehow the best answer doesn't work for me. I need to use a slightly different code instead.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");
I hope this help those who encounters the same issue.
If you use Guava:
import com.google.common.io.Resources;
we can get URL from CLASSPATH:
URL resource = Resources.getResource("test.txt");
String file = resource.getFile(); // get file path
or InputStream:
InputStream is = Resources.getResource("test.txt").openStream();
Ways to convert an InputStream to a String
To read the contents of a file into a String from the classpath, you can use this:
private String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
{
return IOUtils.toString(inputStream);
}
}
Note:
IOUtils is part of Commons IO.
Call it like this:
String fileContents = resourceToString("ImOnTheClasspath.txt");
You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".
Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.
There are these solutions:
Start a new console after every change
Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.
Put the call to Java into .BAT file and double click it. This will create a new console every time (thus copying the current value of the system variable).
BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH=) rather than relying on a global system or user variable.
This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.
My answer is not exactly what is asked in the question. Rather I am giving a solution exactly how easily we can read a file into out java application from our project class path.
For example suppose a config file name example.xml is located in a path like below:-
com.myproject.config.dev
and our java executable class file is in the below path:-
com.myproject.server.main
now just check in both the above path which is the nearest common directory/folder from where you can access both dev and main directory/folder (com.myproject.server.main - where our application’s java executable class is existed) – We can see that it is myproject folder/directory which is the nearest common directory/folder from where we can access our example.xml file. Therefore from a java executable class resides in folder/directory main we have to go back two steps like ../../ to access myproject. Now following this, see how we can read the file:-
package com.myproject.server.main;
class Example {
File xmlFile;
public Example(){
String filePath = this.getClass().getResource("../../config/dev/example.xml").getPath();
this.xmlFile = new File(filePath);
}
public File getXMLFile() {
return this.xmlFile;
}
public static void main(String args[]){
Example ex = new Example();
File xmlFile = ex.getXMLFile();
}
}
If you compile your project in jar file:
you can put your file in resources/files/your_file.text or pdf;
and use this code:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class readFileService(){
private static final Logger LOGGER = LoggerFactory.getLogger(readFileService.class);
public byte[] getFile(){
String filePath="/files/your_file";
InputStream inputStreamFile;
byte[] bytes;
try{
inputStreamFile = this.getClass().getResourceAsStream(filePath);
bytes = new byte[inputStreamFile.available()];
inputStreamFile.read(bytes);
} catch(NullPointerException | IOException e) {
LOGGER.error("Erreur read file "+filePath+" error message :" +e.getMessage());
return null;
}
return bytes;
}
}
I am using webshpere application server and my Web Module is build on Spring MVC. The Test.properties were located in the resources folder, i tried to load this files using the following:
this.getClass().getClassLoader().getResourceAsStream("Test.properties");
this.getClass().getResourceAsStream("/Test.properties");
None of the above code loaded the file.
But with the help of below code the property file was loaded successfully:
Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.properties");
Thanks to the user "user1695166".
Use org.apache.commons.io.FileUtils.readFileToString(new File("src/test/resources/sample-data/fileName.txt"));
Don't use getClassLoader() method and use the "/" before the file name. "/" is very important
this.getClass().getResourceAsStream("/SomeTextFile.txt");
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile
{
/**
* * feel free to make any modification I have have been here so I feel you
* * * #param args * #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// thread pool of 10
File dir = new File(".");
// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}
}
you have to put your 'system variable' on the java classpath.

Java read file within static method, using ClassLoader gives FileNotFoundException

I want to read a file in my java class. My question is similar to this one, but there are two differences. first, I use a different project layout:
/src/com/company/project
/resources
In the resources folder I have a file called "test.txt":
/resources/test.txt
In the project folder I have a class test.java
/src/com/company/project/test.java
I want mu java class to be able to read the contents of test.txt in a STATIC METHOD. I've tried the following:
private static String parseFile()
{
try
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String fileURL = classLoader.getResource("test.txt").getFile();
File file = new File(fileURL);
...
}
}
and the following paths:
File file1 = new File("test.txt");
File file2 = new File("/test.txt");
File file3 = new File("/resources/test.txt");
But they all throw a FileNotFoundException when I want to read the file. How can I correctly declare the path to my file in the snippet above with respect to my project setup and the fact that the method needs to be static?
You should use the class loader of the class which is in the same JAR as the resource instead of the TCCL. And then you need to specify the name of the resource with a full path. And it is typically not good to access those as files. Just open it directly for read (or copy it to a temp file if you need to):
InputStream is =
Project.class.getClassLoader().getResourceAsStream("/resource/test.txt");
BTW: if you simply want to open a file, you need to use a relative file name. This is searched relative to the start dir, which is normally the project main dir (in eclipse):
File resource = new File("resource/test.txt");
(but this wont work if you package it up as a JAR).
After endless trials, I gave up on ClassLoader and getResource methods of any kind.
Absolutely nothing worked, especially if the opening attempt was made from another project. I always ended up getting the bin folder instead of the src folder.
So I devised the following work around:
public class IOAccessory {
public static String getProjectDir() {
try {
Class<?> callingClass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());
URL url = callingClass.getProtectionDomain().getCodeSource().getLocation();
URI parentDir = url.toURI().resolve("..");
return parentDir.getPath();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return "";
}
}
The getProjectDir method returns the physical path of the project from which it was called, e.g. C:/workspace/MyProject/.
After that, all you need to do is concatenate the relative path in MyProject of your resource file to open the stream:
public void openResource() throws IOException {
InputStream stream = null;
String projectDir = IOAccessory.getProjectDir();
String filePath = "resources/test.txt";
try {
stream = new FileInputStream(projectDir + filePath);
open(stream);
} catch(Exception e) {
e.printStackTrace();
} finally {
if (stream != null)
stream.close();
}
}
This technique works whether the openResource method is static or non-static, and whether it is called from within the project or from another project on the build path.
It really depends on how your IDE generates output from your project. Typically, classloaders load resources relative to the invoking classes, but if treated right, 'resources' will just end up in the 'root' of your output folder hierarchy, and you can access them accordingly.
For example, if I recreate your code in IntelliJ IDEA, in a class called com/acme/TestClass.class, the following output structure is generated within the IDE when building. This assumes I have "test.txt" sitting in a folder I called "resources", and that folder is specified as being a "resources root":
/com
/acme
TestClass.class
test.txt
The text file ends up in the output folder's root, so accessing it is simple. The following code works for me when I attempt to load the file in a static method within TestClass:
ClassLoader cl = TestClass.class.getClassLoader();
InputStream is = cl.getResourceAsStream("test.txt");
The only thing not covered in the other answers is that your URL conversion to file might not work correctly. If the directories above your project contain a characters that must be decoded then your call to 'getResource("test.txt").getFile()' is not giving you a valid java.io.File path.
I load shader for openGL ES from static function.
Remember you must use lower case for your file and directory name, or else the operation will be failed
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
public static int loadShader() {
// Read file as input stream
InputStream inputStream = MyGLRenderer.class.getResourceAsStream("/res/raw/vertex_shader.txt");
// Convert input stream to string
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String shaderCode = s.hasNext() ? s.next() : "";
}
...
}
Another method to convert input stream to string.
byte[] bytes;
String shaderCode = "";
try {
bytes = new byte[inputStream.available()];
inputStream.read(bytes);
shaderCode = new String(bytes);
}
catch (IOException e) {
e.printStackTrace();
}

How to import an Image to Project resource folder

I'm developing a java based application using NetBeans.
What i want to do:
My project folder includes a resources folder which contains all the Images that are needed by the project for basic stuff (setting background,icons etc).
Now suppose end user wants to save an new Image on the run time. File Chooser opens up. User selects a source(.jpg) file and the image gets copied. What i want is, to save this image to my resources folder rather than on LocalDisk path. I'm having no trouble copying this image to a LocalDisk path.
Is there any way through which i can do this?
My resource folder path is:
(ProjectName)\src\resources
Code I'm using to save image to Local Address:
InputStream input = null;
OutputStream output = null;
String fileName = itemId.getText();
try
{
input = new FileInputStream(srcPath.getText()); //Getting Source File Absolute Path Through FileChooser
output = new FileOutputStream("C:\\Users\\BUN\\Documents\\Folder\\"+fileName+".jpg");
byte[] buf = new byte[1024];
int bytesRead;
while((bytesRead = input.read(buf))>0)
{
output.write(buf,0,bytesRead);
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
Thank's in advance!

My java code is flawed, but i dont understand why

I am very new at java and my be missing something very basic. When i run my code i am trying to add value to accounts created in the code. When i try to run the code i recieve an error that a file cannot be found, but i thought that the file was created inside the code.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class DoPayroll
{
public static void main(String args[])
throws
IOException
{
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
for (int empNum = 1; empNum <= 3; empNum++)
{
payOneEmployee(diskScanner);
}
}
static void payOneEmployee(Scanner aScanner)
{
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
aScanner.nextLine();
}
}
once run i recieve the following error
Exception in thread "main" java.io.FileNotFoundException: EmployeeInfo.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at DoPayroll.main(jobexe.java:11)
i thought that in the above code using new Scanner(new File("EmployeeInfo.txt") would create the new file once i input a value. Please give me a simple solution and an explanation.
It will create a new file when you write to it. However to read from it, it must already exist. You might like to check it exists with
File file = new File("EmployeeInfo.txt");
if (file.exists()) {
Scanner diskScanner = new Scanner(file);
for (int empNum = 1; empNum <= 3; empNum++)
payOneEmployee(diskScanner);
}
The File object can't find the filename you've passed. You either need to pass the full path of EmployeeInfo.txt to new File(...) or make sure current working directory is the directory that contains this file.
The File constructor does not create a file. Rather, it creates the information in Java needed to access a file on disk. You'd have to actually do file IO in Java using the created File for a new file to be created.
The Scanner constructor requires an existing File. So you need a full path to the real, valid location of EmployeeInfo.txt or to create that file using File I/O first. This tutorial on I/O in Java will help.
You are mistaking instantiating an instance of class File with actually writing a temp file to Disk. Take this line
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
And replace it with this
File newFile = File.createTempFile("EmployeeInfo", ".txt");
Scanner diskScanner = new Scanner(newFile);
Edit: Peter makes a good point. I'm face palming right now.
You thought wrong :D A Scanner needs a existing file, which seems quite logical as it reads values and without a existing file its difficult to read. The documentation also states that:
Throws:
FileNotFoundException - if source is not found
So, in short: You must provide a readable, existing file to a scanner.
As the other answer explain, the file is not created just by using new File("EmployeeInfo.txt").
You can check is the file exists using
File file = new File("EmployeeInfo.txt");
if(file.exists()) {
//it exists
}
or you can create the file (if it doesn't exists yet) using
file.createNewFile();
that method returns true if the file was created and false if it already existed.

How to read text file from classpath in Java?

I am trying to read a text file which is set in CLASSPATH system variable. Not a user variable.
I am trying to get input stream to the file as below:
Place the directory of file (D:\myDir) in CLASSPATH and try below:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
Place full path of file (D:\myDir\SomeTextFile.txt) in CLASSPATH and try the same above 3 lines of code.
But unfortunately NONE of them are working and I am always getting null into my InputStream in.
With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
If those aren't working, that suggests something else is wrong.
So for example, take this code:
package dummy;
import java.io.*;
public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
And this directory structure:
code
dummy
Test.class
txt
SomeTextFile.txt
And then (using the Unix path separator as I'm on a Linux box):
java -classpath code:txt dummy.Test
Results:
true
true
When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.
Resource resource = new ClassPathResource("com/example/Foo.class");
Through the Resource interface you can access the resource as InputStream, URL, URI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.
This is how I read all lines of a text file on my classpath, using Java 7 NIO:
...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
...
Files.readAllLines(
Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());
NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.
Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets
(these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").
Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8
Please try
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
Your tries didn't work because only the class loader for your classes is able to load from the classpath. You used the class loader for the java system itself.
To actually read the contents of the file, I like using Commons IO + Spring Core. Assuming Java 8:
try (InputStream stream = new ClassPathResource("package/resource").getInputStream()) {
IOUtils.toString(stream);
}
Alternatively:
InputStream stream = null;
try {
stream = new ClassPathResource("/log4j.xml").getInputStream();
IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
To get the class absolute path try this:
String url = this.getClass().getResource("").getPath();
Somehow the best answer doesn't work for me. I need to use a slightly different code instead.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");
I hope this help those who encounters the same issue.
If you use Guava:
import com.google.common.io.Resources;
we can get URL from CLASSPATH:
URL resource = Resources.getResource("test.txt");
String file = resource.getFile(); // get file path
or InputStream:
InputStream is = Resources.getResource("test.txt").openStream();
Ways to convert an InputStream to a String
To read the contents of a file into a String from the classpath, you can use this:
private String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
{
return IOUtils.toString(inputStream);
}
}
Note:
IOUtils is part of Commons IO.
Call it like this:
String fileContents = resourceToString("ImOnTheClasspath.txt");
You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".
Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.
There are these solutions:
Start a new console after every change
Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.
Put the call to Java into .BAT file and double click it. This will create a new console every time (thus copying the current value of the system variable).
BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH=) rather than relying on a global system or user variable.
This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.
My answer is not exactly what is asked in the question. Rather I am giving a solution exactly how easily we can read a file into out java application from our project class path.
For example suppose a config file name example.xml is located in a path like below:-
com.myproject.config.dev
and our java executable class file is in the below path:-
com.myproject.server.main
now just check in both the above path which is the nearest common directory/folder from where you can access both dev and main directory/folder (com.myproject.server.main - where our application’s java executable class is existed) – We can see that it is myproject folder/directory which is the nearest common directory/folder from where we can access our example.xml file. Therefore from a java executable class resides in folder/directory main we have to go back two steps like ../../ to access myproject. Now following this, see how we can read the file:-
package com.myproject.server.main;
class Example {
File xmlFile;
public Example(){
String filePath = this.getClass().getResource("../../config/dev/example.xml").getPath();
this.xmlFile = new File(filePath);
}
public File getXMLFile() {
return this.xmlFile;
}
public static void main(String args[]){
Example ex = new Example();
File xmlFile = ex.getXMLFile();
}
}
If you compile your project in jar file:
you can put your file in resources/files/your_file.text or pdf;
and use this code:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class readFileService(){
private static final Logger LOGGER = LoggerFactory.getLogger(readFileService.class);
public byte[] getFile(){
String filePath="/files/your_file";
InputStream inputStreamFile;
byte[] bytes;
try{
inputStreamFile = this.getClass().getResourceAsStream(filePath);
bytes = new byte[inputStreamFile.available()];
inputStreamFile.read(bytes);
} catch(NullPointerException | IOException e) {
LOGGER.error("Erreur read file "+filePath+" error message :" +e.getMessage());
return null;
}
return bytes;
}
}
I am using webshpere application server and my Web Module is build on Spring MVC. The Test.properties were located in the resources folder, i tried to load this files using the following:
this.getClass().getClassLoader().getResourceAsStream("Test.properties");
this.getClass().getResourceAsStream("/Test.properties");
None of the above code loaded the file.
But with the help of below code the property file was loaded successfully:
Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.properties");
Thanks to the user "user1695166".
Use org.apache.commons.io.FileUtils.readFileToString(new File("src/test/resources/sample-data/fileName.txt"));
Don't use getClassLoader() method and use the "/" before the file name. "/" is very important
this.getClass().getResourceAsStream("/SomeTextFile.txt");
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile
{
/**
* * feel free to make any modification I have have been here so I feel you
* * * #param args * #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// thread pool of 10
File dir = new File(".");
// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}
}
you have to put your 'system variable' on the java classpath.

Categories