I have a certain requirement where I need to copy files from Unix server to Windows Shared Drive. I am developing the necessary code for this in Java. I am a beginner so please excuse me for this basic question.
I have my source path in my config file. So, I am using the below code to import my config file and set my variable. My Project has config.properties file attached to it.
public static String rootFolder = "";
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Config files not able to set properly for Dest Folder");
}
try {
prop.load(input);
rootFolder = prop.getProperty("Dest_Root_Path");
System.out.println("Destination Folder is being initialized to - "+rootFolder);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Destination Path not set properly");
}
When I am doing this I am getting an error saying the file is not found.
java.io.FileNotFoundException: config.properties (No such file or directory)
at java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.io.FileInputStream.<init>(FileInputStream.java:113)
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties.load(Properties.java:357)
I am triggering this jar using a unix ksh shell. Please provide guidance to me.
Put your config file somewhere within the classpath. For example, if it's a webapp, in WEB-INF/classes. If it isn't a webapp, create a folder outside the project, put the file there, and set the classpath so the new folder is in it.
Once you have your file in the classpath, get it as a resource with getResourceAsStream():
InputStream is = MyProject.class.getResourceAsStream("/config.properties");
Don't forget the slash / before the filename.
Related
I need to get this file from the resources folder in the File object, not in InputSream.
I am using below code, working file on eclipse but FoleNotFoundException on the server. )Using AWS EC2)
Code:
URL res = ResidentHelperService.class.getClassLoader().getResource("key.pem");
System.out.println("resource path2 :" + res);
File privateKeyFile = Paths.get(res.toURI()).toFile();
After printing path looks like:
:jar:file:/home/centos/myproject/microservices/user-service/target/user-service-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/project-common-utility-0.0.1-SNAPSHOT.jar!/key.pem
I have added dependency on the common jar to user service pom.
Please help me to get the file from resources of a common project.
If you have your file in resources folder, the easiest way to access it from the code is probably to use org.springframework.util.ResourceUtils class that Spring provides:
try {
final File file = ResourceUtils.getFile("classpath:key.pem");
....
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Perhaps this way can help you with your issue.
With reference to the link: How do I read a resource file from a Java jar file?
I am trying using your code base and trying to read content of sample.csv which is residing in my project directory src/main/resources. I am unable to read the content, it says can not read file. Output:
[Can not read file: sample.csv]
//This is added within your while loop after this check /* If it is a directory, then skip it. */
I mean when file is detected then next is my below code snippet added to read the file content
if(entry.getName().contains("sample.csv")) {
File f1 = new File("sample.csv");
if(f1.canRead()) {
List<String> lines = Files.readAllLines(f1.toPath());
System.out.println("Lines in file: "+lines.size());
} else {
System.out.println("Can not read file: "+entry.getName());
}
}
Can anyone educate me what I am doing wrong here, how can I make it working?
My requirement is this:
(My micro-service) Service.jar imports Parser.jar library in its pom.xml
(My library) - Parser.jar has FnmaUtils-3.2-fieldMapping.csv file in src/main/resources directory
There is a FnmaUtils class that loads the FnmaUtils-3.2-fieldMapping.csv within its constructor, this class is part of Parser.jar - Here I am trying to read the content FnmaUtils-3.2-fieldMapping.csv, this step is keep failing with below error, tried all possible options shown in [How do I read a resource file from a Java jar file?
public FnmaUtils() {
String mappingFileUrl = null;
try {
Resource resource = new ClassPathResource("FnmaUtils-3.2-fieldMapping.csv");
mappingFileUrl = resource.getFile().getPath();
loadFnmaTemplate(mappingFileUrl);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error loading fnma template file ", e);
}
}
Getting error:
java.io.FileNotFoundException: class path resource [`FnmaUtils-3.2-fieldMapping.csv`] cannot be resolved to absolute file path because it does not reside in the file system: `jar:file:/home/ravibeli/.m2/repository/com/xxx/mismo/util/fnma-parser32/2018.1.0.0-SNAPSHOT/fnma-parser32-2018.1.0.0-SNAPSHOT.jar!/FnmaUtils-3.2-fieldMapping.csv`
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:218)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:52)
at com.xxx.fnma.util.FannieMaeUtils.<init>(FannieMaeUtils.java:41)
at com.xxx.fnma.processor.FNMA32Processor.<init>(FNMA32Processor.java:54)
at com.xxx.fnma.processor.FNMA32Processor.<clinit>(FNMA32Processor.java:43)
What is going wrong here?
Try
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
Be sure the resource is in your classpath.
I tried to open file form my java application. Using following code from
Open PDF file on fly from Java application
Code:
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
When I use path like :
"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf"
it opens. But my file is inside my package
files/test.pdf
and I used
files\\test.pdf
it shows following exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.
Why? Any Idea... I want to include my file inside my jar file that can open from my application whenever user wants.
Thanks...
getDesktop#open only allows files to be opened from the file system. One solution is to keep the PDF file locally on the file system and read from there. This eliminates extracting the file from the JAR itself so is more efficient.
Unfortunately, you cannot load a file through Desktop that is contained in the jar.
However, you are not out of options. A great workaround is to create a temporary file and then open it as detailed here.
Good luck!
Assuming test.pdf is in the package files, try this:
File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
This code is working properly please use this to open pdf file within jar file
try {
// TODO add your handling code here:
String path = jTextField1.getText();
System.out.println(path);
Path tempOutput = null;
String tempFile = "myFile";
tempOutput = Files.createTempFile(tempFile, ".pdf");
tempOutput.toFile().deleteOnExit();
InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
if(Desktop.isDesktopSupported())
{
Desktop dTop = Desktop.getDesktop();
if(dTop.isSupported(Desktop.Action.OPEN))
{
dTop.open(tempOutput.toFile());
}
}
} catch (IOException ex) {}
So I'm trying to read in from a config file in my Eclipse project, but it can't locate the file. Here's my code.
public void readConfigFile () {
//URL url = Test.class.getClassLoader().getResource("myfile.txt");
//System.out.println(url.getPath());
URL url = getClass().getResource("/config");
System.out.println(url);
try {
BufferedReader read = new BufferedReader(new FileReader(url.toString()));
//read in values for constants from config file
System.out.println(BASE_URL);
BASE_URL = read.readLine().split("\t")[1];
System.out.println(BASE_URL);
read.close();
}
catch (Exception e)
{
System.out.println("Read from config file failed. Terminating program");
System.out.println(e);
System.exit(1);
}
}
When I run, it prints the url variable as:
/Users/myname/Development/workspace/New_API/bin/config
But it fails to find the file when running the BufferedReader command. I get:
Read from config file failed. Terminating program
java.io.FileNotFoundException:
file:/Users/myname/Development/workspace/New_API/bin/config.txt (No such file or directory)
When I go to the bin directory of my code however, the config file is there. In the root bin directory, following the exact path given by the URL. What is messing Eclipse up?
When getting a resource from the class loader, you're getting it from the classpath, not from the file system. If your application was packaged as a jar, you wouldn't have access to the resource through the File or FileInputStream APIs since the resource is part of the archive. Instead, you can access the input stream of the resource like so:
URL url = getClass().getResource("/config");
BufferedReader read = new BufferedReader(new InputStreamReader(url.openStream()));
// more...
propsdatabase = new Properties();
try
{
// load a properties file
InputStream dbin = getClass().getResourceAsStream("/database.properties");
//props.load(in);
propsdatabase.load(dbin);
}
catch (IOException ex)
{
ex.printStackTrace();
}
I Want to access a file which is out of the jar file. just in the location of the jar file.
I am using a properties file named database.properties in main/resources folder .
The requirement is to change the location of database.properties outside the jar.
So I need something where the path can point to the location where the jar is .
I am using maven to build my jar
FileInputStream dbin = new FileInputStream("/my/folder/database.properties");
You can do it in two ways by defining absolute path for the pro
Class.getResourceAsStream ("/some/pkg/resource.properties");
And
ResourceBundle.getBundle ("some.pkg.resource");