Create a java file inside a package - java

Currently, my plugin creates a java file in my project(IProject). But I want that java file within a specified Package. How to do it.
IFile sampleFile = parentFolder.getFile("Sample.java");
if(!sampleFile.exists()) FileInputStream fileStream = new FileInputStream("C:\Users\Uma\Desktop\treasureHunt\Application.java"); sampleFile.create(fileStream, false, null);
This is my current piece of code.
How can I create the sampleFile within a package. For example: in package com.mdh.se as com.mdh.se.Sample.java

If you have a "package" (e.g. "com.mdh.se") then you'll have a corresponding subdirectory (for example, "c:\users\uma\desktop\treasurehunt\com\mdh\se"). Simply write your file there.

I think, that the only thing you need to do is to create folders representing your package structure. So your path should look like C:\Users\Uma\Desktop\treasureHunt\com\mdh\se\Sample.java for your example.

You can get a special file inside the package by calling
java.net.URL imgURL = ResourceManager.class.getResource( "ResourceManager.class" );
From these URL you can extract the directory, the file is placed.
A new file you can create with
new File(directory,filename);

Related

How to not hard-code a file path

I'd like to calculate the path of a file placed into Source Packages using this implementation:
URL pathSource = this.getClass().getResource("saveItem.xml");
When I try to create a new File like the code below:
File xmlFile = new File(pathSource.toString());
And I try to use it to create a document like this:
Document document = builder.parse(xmlFile);
This give me the java.io.FileNotFoundException.
How can I calculate the file path without hard-coding?
PS: I already used pathSource.getPath() but it doesn't work either.
I would like to use a similar implementation:
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
PPS: The structure is the following:
You can't access a resource that inside a JAR file as a File instance. You can only get an InputStream to it.
As such, the following line
File xmlFile = new File(pathSource.toString());
won't work properly and when an attempt is made to read it later, a FileNotFoundException will be thrown.
Assuming you're trying to parse a XML file using DocumentBuilder, you can use the parse(InputStream) method:
try (InputStream stream = this.getClass().getResourceAsStream("saveItem.xml")) {
Document document = builder.parse(stream);
}
Short answer - saveItem.xml is not in the classpath.
If it is a web application, then file may be added to WEB-INF/classes folder.
Edit:
Try this.getClass().getResourceAsStream() too.
getClass().getResource("saveItem.xml");
looks for the file in the same package (which are directories when you look at the file system) as the class that getClass() returns.
Make sure the file is in there. Also make sure it's really in there when you run your code, there's a difference between your source folder and the target or bin folder where the compiled class files are placed.
Also check what pathSource.toString() contains.

How to read properties file inside jar?

I have a config.properties file under the package com.abc.properties. From one of the java class present in com.abc.util, I need to read the property file. Both the files are present inside jar.
I have tried using
fs = new FileInputstream(VerifyFolderStructure.class.getResourceAsStream("com/abc/properties/config.properties"));
But it doesn't seem to work. Please help.
P.S: VerifyFolderStructure is my java class from which I need to load the properties file.
To obtain the stream you don't need FileInputStream at all. You can get the properties' file stream like this
InputStream is = VerifyFolderStructure.class.getResourceAsStream("/com/abc/properties/config.properties");
I think you need to add "/" in the front of you path.if you don't add "/" that means the properties is located in the same packages path as VerifyFolderStructure class.

Can I use File.createTempFile() to create a file with a non-random name

I want to create a temporary file (that goes away when the application closes) with a specific name. I'm using this code:
f = File.createTempFile("tmp", ".txt", new File("D:/"));
This creates something like D:\tmp4501156806082176909.txt. I want just D:\tmp.txt. How can I do this?
In this case, don't use createTempFile. The point of createTempFile is to generate the "garbage" name in order to avoid name colisions.
You should use File.createNewFile() or simply write to the file. Whichever is more appropriate for your use case. You can then call File.deleteOnExit() to get the VM to look after cleaning up the file.
If you want to create just tmp.txt, then just create the file using createNewFile(), instead of createTempFile(). createTempFile is used to create temporary files that should not have the same name when created over and over.
Also have a look at this post which shows a very simple way to create files.
Taken the post mentioned above:
String path = "C:"+File.separator+"hello"+File.separator+"hi.txt";
//(use relative path for Unix systems)
File f = new File(path);
//(works for both Windows and Linux)
f.mkdirs();
f.createNewFile();
try regex
fileName = fileName.replaceAll("\\d", "");

Path to a file inside a package

Is there a way to read a text file which is inside a package.
Lets say that I want to access a file called "myTextFile.txt", which is in a package called "a".
I want to access it from a class called "MyClass" which is in the same package.
What would be the path to "myTextFile.txt"? And would I be able to use bufferedreader like this: BufferedReader in = new BufferedReader(new FileReader(PATH));
Where is your project compiled to? Any paths will be relative to the program's location, or the full path if you specify, not the class. Once you get that path you can put it where PATH is.
However, is there any reason you're putting that file inside a package? Shouldn't it go in some sort of resources directory?
GetResource on Class works well. ResourceLocator in Spring is also a very flexible option as well.
You can get always get resources via ClassLoader.getResourceAsStream() (or getResource()). They can also be accessed via Class.getResourceAsStream() (instead of ClassLoader). You could either use relative or absolute names (starting with /).
It sounds like you need to use one of the Class.getResource() or ClassLoader.getResource() methods:
URL url = MyClass.class.getResource("myTextFile.txt");
URL url = MyClass.class.getClassLoader().getResource("myTextFile.txt");
or
InputStream in = MyClass.class.getResourceAsStream("myTextFile.txt");
InputStream in = MyClass.class.getClassLoader().getResourceAsStream("myTextFile.txt");
See this question for a comparison, and an explanation of absolute versus relative paths.
Then you could do
new BufferedReader(new InputStreamReader(in));
InputStream is = new BufferedInputStream(
getClass().
getClassLoader().
getResourceAsStream("/a/myTextFile.txt"));
Should do the trick. Note please the structure of the arg, the root of the package is represented by "/" and so are your packages (i.e. directories)
Just input the absoulte file path. i.e. your lcoal machine path. Should work.

Reading .txt file from another directory

The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file

Categories

Resources