reading directory path from properties file - java

I need to know that how to read the directory path from a .properties file in java.
for example,
class clazz
{
string filename="d:/file.txt";
public void somemethod()
{
FileWriter f=new FileWriter(filename, true);
// etc
}
i want to read the filename from .properties file rather than from a variable.
how it can be done?

A fairly simple way is to use a resource file, through the ResourceBundle class.
ResourceBundle bundle = ResourceBundle.getBundle("com/file");
Where com/file is the file.properties in the com package.
This file could have a line like this:
file.name=C:\dir\file.txt
For get this particular data.
String filename = bundle.getString("file.name");
I hope this can help you. Good luck!

Check out the Properties class load() method. It reads in a file (in the common properties format) and then you can query the value of a property based on its name

If the properties file is in your class path then do this:
Properties prop = new Properties();
prop.load(this.getClass().getClassLoader().getResourceAsStream("file.txt"));
Sting fileName = prop.get("fileName");

Related

how to read a file from resources folder in properties file

I have a file under resources folder src/test/resources/file.xml
and another under src/test/resources/test.properties. I want to set a property in properties file to point to file.xml. How can I achieve this?
Say I have a property
test.file = file.xml
and my java class reads the file as follows:
File cert = new File(fileName); // fileName is the value of test.file
This does not work however.
You can use Properties class to read and write to config files.
Firstly, you need to find the relative path for the resources using
below steps
Secondly, you can configure and load the test properties file
Finally, read the property value and append with the resource
directory
Code:
String rootDirectory=System.getProperty("user.dir");
String resourceDirectory=rootDirectory+"src/test/resources/";
//Configure property File
Properties properties = new Properties();
properties.load(new FileInputStream(resourceDirectory+"test.properties"));
PropertyConfigurator.configure(properties);
//To get the property value
String tempFileName=properties.getProperty("test.file");
//filename Needs to be changed as below
File cert = new File(resourceDirectory+tempFileName);

File not being Created

I am creating a file like this (I am sending arg[0] as the name of the file to be created).
No file is created I searched through the source of the project and found nothing, why?
import java.io.File;
public class Test {
public static void main (String [] args)
{
File f=new File(args[0]);
}
}
Try with
File f=new File(args[0]);
f.createNewFile();
File is just a representation of the path. You need to actually open an output stream with that file and write to that for a file to be created.
This is normal.
A File is an abstract object. It may, or may not, refer to an existing resource on the filesystem.
But since this is 2015, drop File, use java.nio.file instead:
final Path path = Paths.get(args[0]);
Files.createFile(path);
But really, you shouldn't use File in 2015. Seriously. Yes, .createNewFile() exists on File but... Well, read the page. In short: returns a boolean, need to check the return value, if false, SOL, you can't even diagnose.
Edit: a page to learn how to use java.nio.file: here
(shameless self-advertising for both links, sorry for that)
Just creating file object does not create physical file on disk.Actual file is created with f.createNewFile() as explained in below demo
When yo do File file=new File(args[0]); file just represents the java object not the file object on file system
Here is demo for basic file create and delete operations
public class FileDemo {
public static void main(String[] args) {
File f = null;
try{
// create new file
f = new File("test.txt");
// tries to create new file in the system
f.createNewFile();
// deletes file from the system
f.delete();
}catch(Exception e){
e.printStackTrace();
}
}
}
Executing new File(...) does not create a file in the file system. A File object is just a way of representing the path for a file system object that may or may not existing.
The typical way to create a file is to open a FileOutputStream or FileWriter for the file. The file is created even if you don't write anything. Other alternatives are to call File.createNewFile() or File.createTempFile(...).

Relative path to store a file in any computer - Java

I have used this reference to read a file on my project. but i need to store likewise i don't know how to do this? please help me.
for reading a file i have taken the code from the link
InputStream csv =
SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");
Like this can anyone help me with writing a file
currently I'm using this code:
Writer output = null;
output = new BufferedWriter(new FileWriter("./filename.csv"));
But it throws FileNotFound Exception at runtime
Issue is with locating file path. it works fine if i give absolute path. but it needs to be run in any computer
The FileWriter will create files as required. It doesn't have to exist already.
The only way you can get this error is if the current working directory no longer exists or you don't have permission to create a file in the directory.
Check your permissions:
Writer output = null;
if (new File("./filename.csv").canWrite()) {
System.out.println("You have not permissions");
} else {
output = new BufferedWriter(new FileWriter("./filename.csv"));
...
}
OK..Use the following code to get the path of file:
String path = System.getProperty("user.dir");
FileWriter fw = new FileWriter(path+File.separator+"filename.csv");
EDIT
Here is a Demo Code that is creating file "pqr.txt" in package myPackage. Given that I am executing the class file using command java myPackage.AccessCheck i.e from one directory above the mypackage.
package myPackage;
import java.io.FileWriter;
import java.io.File;
public class AccessCheck
{
protected void callme()
{
try
{
String name = System.getProperty("user.dir")+File.separator+AccessCheck.class.getPackage().getName()+File.separator+"pqr.txt";
System.out.println(name);
FileWriter fw = new FileWriter(name);
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String st[])
{
AccessCheck asc = new AccessCheck();
asc.callme();
}
}
Instead of calling getResourceAsStream(), call class.getResource() or classLoader.getResource(). These functions return a URL giving the location of the resource. If the resource is a plain file on the filesystem, the URL will be a file: URL.
Once you have the URL, you can convert it to a URI and pass it to the File constructor which takes a URI. Then you can use the File object to open the file.
Note that getResource() can return URLs that the File constructor can't deal with. For example, if the resource is found in a jar file, then the URL might look like this:
jar:file:/C:/path/to/JDK/lib/vm.jar!/java/lang/Object.class
The File constructor can't deal with URLs like this. This may or may not be a concern for you.

Unable to read Java File from JSF

The directory structure of my application is as follows:-
My App
++++++ src
++++++++com
++++++++++readProp.java
++++++++resource
++++++++++message.properties
I am trying to read the file as follows:-
public Static final string FilePath="resource.message.properties"
Here the code to read the file. I tried using the following two techniques but to no use...
File accountPropertiesFile = new File(FacesContext.getCurrentInstance()
.getExternalContext().getRequestContextPath()
+ FilePath);
properties.load(externalContext.getResourceAsStream(FilePath));
But none yeild any sucess while reading through the Bean class. please help...
Your properties file is in the classpath. The java.io.File only understands the local disk file system structure. This is not going to work. You need to get it straight from the classpath by the classloader.
Here's a kickoff example:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/messages.properties");
if (input != null) {
Properties properties = new Properties();
try {
properties.load(input);
} finally {
input.close();
}
}
I don't know if this is your problem, but you should try using slashes instead of periods, since they're stored as actual folders in the filesystem.

How to read file from relative path in Java project? java.io.File cannot find the path specified

I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

Categories

Resources