java.io.FileNotFoundException - Can't read my properties file - eclipse

Eclipse/Linux - Java Web Application.
I added a file named dao.properties to my project. I put it in a package : com.cdp.dao . My class which uses this file is in the same package.
When I try to load it I have a
java.io.FileNotFoundException
/myproject/src/com/cdp/dao/dao.properties (No such file or directory) OR
dao.properties (No such file or directory)
This my code :
Properties prop;
FileInputStream fis;
File file = new File("/myproject/src/com/cdp/dao/dao.properties");
//File file = new File("dao.properties"); doesn't work either
try {
prop = new Properties();
fis = new FileInputStream(file);
prop.load(fis);
dbUrl = prop.getProperty("dbUrl");
user = prop.getProperty("user");
pwd = prop.getProperty("pwd");
driver = prop.getProperty("driver");
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Use
this.getClass().getResourceAsStream("dao.properties");
to load the properties file

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("/dir/SomeTextFile.txt");
but if you need to use classpath use just filename like below
InputStream in = this.getClass().getResourceAsStream("dao.properties");

Related

How to set the path of the file writer to location of the jar using it?

So i recently switch from starting the jar file from a service rather than a script that first goes to the relevant directory. Is there a way to make sure that the path to the jar file is used instead of wherever the service started it? Inside the application i use the code below to get the correct path.
try {
Path p = Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
workPath = p.getParent().toString();
if( workPath.matches(".*[lib]")) { // Meaning used as a lib
workPath = Path.of(workPath).getParent().toString();
}
settingsFile = Path.of(workPath, "settings.xml");
} catch (URISyntaxException e) {
Logger.error(e);
}
Store your work path as system property:
try {
Path p = Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
workPath = p.getParent().toString();
if(workPath.matches(".*[lib]")) { // Meaning used as a lib
workPath = Path.of(workPath).getParent().toString();
}
System.setProperty("tinylog.directory", workPath); // Set work path as system property
settingsFile = Path.of(workPath, "settings.xml");
} catch (URISyntaxException e) {
Logger.error(e);
}
Use the system property in tinylog.properties:
writer = file
writer.file = #{tinylog.directory}/log.txt
writer.format = {date: HH:mm:ss.SSS} {level}: {message}

generate pdf file using fop in .net core 3.1

To generate pdf file from fop file I Used FOP.dll and It work well in .net 4.5
public string GeneratePdf(string foFile, string pdfFile)
{
java.io.OutputStream os = new java.io.BufferedOutputStream(new java.io.FileOutputStream(new java.io.File(pdfFile)));
string ret = "";
try
{
org.apache.fop.apps.FopFactory fopFactory = org.apache.fop.apps.FopFactory.newInstance();
fopFactory.setUserConfig(new java.io.File("fo-config.xml"));
org.apache.fop.apps.Fop fop = fopFactory.newFop("application/pdf", os);
org.apache.fop.apps.FOUserAgent foUserAgent = fop.getUserAgent();
javax.xml.transform.TransformerFactory factory = javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = factory.newTransformer();
javax.xml.transform.Source src = new javax.xml.transform.stream.StreamSource(new java.io.File(foFile));
javax.xml.transform.Result res = new javax.xml.transform.sax.SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
ret = pdfFile;
}
catch (Exception ex)
{
throw ex;
}
finally
{
os.close();
}
return ret;
}
but when Convert my Code To .net Core 3.1, It Not Working.
java.io.File throw exception: "System.TypeInitializationException: 'The type initializer for 'java.io.File' threw an exception".
the Inner Exception Is :"Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified"
How can I convert a FOP file to PDF exclusively using .netcore 3.1

How to check for string endings for loading save files?

I need to know how to check for the endings of all the files in the Assets folder.
Its for creating a list of saved files.
public static void Load()
{
if (File.Exists(Application.dataPath + "/data1.sav"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.dataPath + "/data1.sav", FileMode.Open);
SaveLoad.savedData = (List<saveData>)bf.Deserialize(file);
file.Close();
}
}
^this load function works fine.
Now i need something like this:
(pseudocode)
if (File.Exists(With the ending: ".sav") ????
{
Create a list of all those files in a String Array!
}
so if i would have in the Assets folder:
"data1.sav"
"data2.sav"
"test.sav" it should return a String Array with the
size of 3 and which include ["data1.sav"], ["data2.sav"] and ["test.sav"]
Just use GetFiles()
Code would be something like:
string[] files = Directory.GetFiles(DirectoryPath, "*.sav");

Reading a file from /etc/designs in java

I'm in need of storing a string in JCR that'll be used in an OSGi bundle(so that it can be modified as needed in CRXde)
I have stored my string at the location /etc/designs/shc/components/linkcheck/regex.txt/jcr:content, where regex.txt is the file that contains my regex string.
I'm using the following code to read that String in a bundle but with no luck. It is throwing NullPointerException at resourceResolver.getResource
Resource dataResource = resourceResolver.getResource("/etc/designs/shc/components/linkcheck/regex.txt/jcr:content");
Node node = dataResource.adaptTo(Node.class);
String regex = node.getProperty("jcr:data").getValue().toString();
regex.txt is of type nt:file and the data is visible in CRXde but the code fails.
Any direction will be highly appreciated!
this should work-
Resource dataResource = resourceResolver.getResource("/etc/designs/shc/components/linkcheck/regex.txt");
Node jcnode = dataResource.adaptTo(Node.class).getNode("jcr:content");
InputStream is = jcnode.getProperty("jcr:data").getBinary().getStream();
StringBuilder sb = new StringBuilder();String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
//do something
}
//do whatever with sb
Since the NullPointerException is thrown at resourceResolver.getResource(...), please check the resourceResolver is not null.

How to programmatically find a .java file in an Eclipse plugin from full classname?

Inside an Eclipse plugin, I'd like to open a file in editor.
I know the full package and class name
How can I determine the path of the .java file from this?
Take a look at IJavaProject.findType( name ) method. Once you have an IType, you can use getPath or getResource methods to locate the file. This method searches across a project and everything visible from that project.
To search the whole workspace, iterate through all the Java projects in the workspace, calling the findType method on each in turn.
You also need to know the source folder.
IProject prj = ResourcePlugin.getWorkspace().getRoot().getProject("project-name");
IFile theFile = prj.getFile(sourceFolder + packageName.replace('.','/') + className + ".java");
Generally you specify the file for an editor with an IFile. You can also ask an IFile for variants of the file's path.
I know this is a bit old but I had the same need and I had a look at how eclipse does it for stack trace elements (they have a hyperlink on them). The code is in org.eclipse.jdt.internal.debug.ui.console.JavaStackTraceHyperlink (the link is "lazy" so the editor to open is resolved only when you click on it).
What it does is it first searches for the type in the context of the launched application, then for in the whole workspace (method startSourceSearch) :
IType result = OpenTypeAction.findTypeInWorkspace(typeName, false);
And then opens the associated editor (method processSearchResult, source is the type retrieved above) :
protected void processSearchResult(Object source, String typeName, int lineNumber) {
IDebugModelPresentation presentation = JDIDebugUIPlugin.getDefault().getModelPresentation();
IEditorInput editorInput = presentation.getEditorInput(source);
if (editorInput != null) {
String editorId = presentation.getEditorId(editorInput, source);
if (editorId != null) {
try {
IEditorPart editorPart = JDIDebugUIPlugin.getActivePage().openEditor(editorInput, editorId);
if (editorPart instanceof ITextEditor && lineNumber >= 0) {
ITextEditor textEditor = (ITextEditor)editorPart;
IDocumentProvider provider = textEditor.getDocumentProvider();
provider.connect(editorInput);
IDocument document = provider.getDocument(editorInput);
try {
IRegion line = document.getLineInformation(lineNumber);
textEditor.selectAndReveal(line.getOffset(), line.getLength());
} catch (BadLocationException e) {
MessageDialog.openInformation(JDIDebugUIPlugin.getActiveWorkbenchShell(), ConsoleMessages.JavaStackTraceHyperlink_0, NLS.bind("{0}{1}{2}", new String[] {(lineNumber+1)+"", ConsoleMessages.JavaStackTraceHyperlink_1, typeName})); //$NON-NLS-2$ //$NON-NLS-1$
}
provider.disconnect(editorInput);
}
} catch (CoreException e) {
JDIDebugUIPlugin.statusDialog(e.getStatus());
}
}
}
}
Code has copyright from eclipse. Hopfully I'm allowed to reproduced it if this is mentionned.