I am unable to read the properties from the file . When I try to print it gives me null, When I debugged I understood it is not loading the file in function
pro.Load(). However my path is correct, still I am unable to load the file
package AdvancedJava;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ReadingPropertiesFile {
public static void main(String[] args) throws FileNotFoundException {
Properties pro = new Properties();
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
// BufferedReader reader = new BufferedReader(new FileReader(path));
File f = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
pro.load(fis);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(pro.getProperty("lastname"));
}
}
Properties file contents
firstname = John
lastname = harry
Automation = Selenium
I think the problem is in path:
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
should be like this:
String path = "C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
Also make sure you have a correct path to your properties file. If it is inside your project, the path should be like this:
String path = "C:\\...\\ProjectFolder\\src\\main\\resources\\object.properties";
Your example works fine for me. Without a stacktrace though, we won't be able to help you regarding the NPE you're getting.
In any way though, I couple of hints regarding your code. I would suggest using a try - with resources when operating with the FileInputStream to make sure that the resource is going to be closed once done.
You can avoid using new File(path);. Instead I would suggest using Paths from the java.nio.* package. An example of this based on your code snippet would be the following:
public static void main(String[] args) {
Properties properties = new Properties();
try (FileInputStream stream = new FileInputStream(Paths.get("E:\\test\\file.txt").toFile())) {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(properties.getProperty("lastname"));
}
The advantage of using Paths is that they're (if not mistaken) system agnostic meaning that you won't need to worry about providing the proper path delimiters.
Actually, path should be with another separator
"C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
but what I should suggest you - it's to store your app properties files under your resource folder, kinda:
src/main/resources/config.properties
than you gonna be able to access this file like this:
public Properties extractFrom(String fileName) {
Properties properties = new Properties();
try (InputStream inputStream = PropertiesExtractor.class
.getClassLoader().getResourceAsStream(fileName)) {
properties.load(inputStream);
} catch (IOException ex) {
throw new RuntimeException("Cannot load properties", ex);
}
return properties;
}
extractFrom("config.properties");
Related
I am facing this issue while reading property file. I searched a lot on the Internet but nothing worked. Below is the code and the image contains the path of the prop.properties file
package Utility;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropUtility {
//private static Properties prop;
private static Properties prop = new Properties();
static {
prop = new Properties();
InputStream in = prop.getClass().getResourceAsStream("/resources/prop.properties");
try {
prop.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getProperty(String key) {
return prop.getProperty(key);
}
}
public static void main(String[] args) throws IOException {
FileReader reader= null;
try {
reader = new FileReader("prop.properties");
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
When you run the code, it cannot access your properties file. You get a nullPointerException error when loading in from that one.
Get your properties file like in the picture below, put it in the project, then run your code. I also made a similar example with FileReader.
Extract from the resource folder. You can read it that way if you import it into the project.
Give this a try.
String inXSL="src/main/resources/abc.xslt";
Here am trying to get the file from the path name and process it but the file is never getting recognized from the given path(JAVA).FYI,the system is MAC.
The file is located inside src/main/resources inside the project.
Please provide inputs on this.
When your application is packaged and built, your file will be placed within the class path of your jar (or war) along with the other classes. It should be loaded using a resource stream. Here is some sample code that would print the contents of the file by loading it from the classpath.
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String[] args) throws InterruptedException {
byte[] contents = new byte[1024];
InputStream inStream = Test.class.getClassLoader().getResourceAsStream("abc.xslt");
BufferedInputStream bis = new BufferedInputStream(inStream);
int bytesRead=0;
String strFileContents = null;
try {
while( (bytesRead = bis.read(contents)) != -1){
strFileContents = new String(contents, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(strFileContents);
}
}
The important line is:
InputStream inStream = Test.class.getClassLoader().getResourceAsStream("abc.xslt");
Depending on your usage, the input stream would be passed into whatever API you are using.
I have an issue.
I have a properties file. I want to store some values in that file and will implement in the code whenever it is required. Is there any way to do that?
I am using Properties class to do that..
Load the properties file using java.util.Properties.
Code snippet -
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("xyz.properties");
prop.load(in);
It provides Properties#setProperty(java.lang.String, java.lang.String) which helps to add new property.
Code snippet -
prop.setProperty("newkey", "newvalue");
This new set you can save using Properties#store(java.io.OutputStream, java.lang.String)
Code Snippet -
prop.store(new FileOutputStream("xyz.properties"), null);
You can do it in following way:
Set the properties first in the Properties object by using object.setProperty(String obj1, String obj2).
Then write it to your File by passing a FileOutputStream to properties_object.store(FileOutputStream, String).
Here is the example code :
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
class Main
{
static File file;
static void saveProperties(Properties p) throws IOException
{
FileOutputStream fr = new FileOutputStream(file);
p.store(fr, "Properties");
fr.close();
System.out.println("After saving properties: " + p);
}
static void loadProperties(Properties p)throws IOException
{
FileInputStream fi=new FileInputStream(file);
p.load(fi);
fi.close();
System.out.println("After Loading properties: " + p);
}
public static void main(String... args)throws IOException
{
file = new File("property.dat");
Properties table = new Properties();
table.setProperty("Shivam","Bane");
table.setProperty("CS","Maverick");
System.out.println("Properties has been set in HashTable: " + table);
// saving the properties in file
saveProperties(table);
// changing the property
table.setProperty("Shivam", "Swagger");
System.out.println("After the change in HashTable: " + table);
// saving the properties in file
saveProperties(table);
// loading the saved properties
loadProperties(table);
}
}
Your problem is not clear since Writing/reading from properties files is something already available in java.
To write to properties file you can use the Properties class as you mentioned :
Properties properties = new Properties();
try(OutputStream outputStream = new FileOutputStream(PROPERTIES_FILE_PATH)){
properties.setProperty("prop1", "Value1");
properties.setProperty("prop2", "Value2");
properties.store(outputStream, null);
} catch (IOException e) {
e.printStackTrace();
}
Source and more examples here
This work for me.
Properties prop = new Properties();
try {
InputStream in = new FileInputStream("src/loop.properties");
prop.load(in);
} catch (IOException ex) {
System.out.println(ex);
}
//Setting the value to our properties file.
prop.setProperty("LOOP", "1");
//Getting the value from our properties file.
String value = prop.getProperty("LOOP").trim();
try {
prop.store(new FileOutputStream("src/loop.properties"), null);
} catch (IOException ex) {
System.out.println(ex);
}
I have a file I'm using to hold system information that my program needs on execution.
The program will read from it and write to it periodically. How do I do this? Among other problems, I'm having trouble with paths
Example
How do I read/write to this properites file if deploying application as runnable jar
Take a look at the http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
You can utilize this class to use your key=value pairs in the property/config file
Second part of your question, how to build a runnable jar. I'd do that with maven, take a look at this :
How can I create an executable JAR with dependencies using Maven?
and this :
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
I see you're not using maven to build your project altogether
You can't write to a file that exists as part of a ZIP file... it does not exist as a file on the filesystem.
Considered the Preferences API?
To read from a file you can declare a file reader using a scanner as
Scanner diskReader = new Scanner(new File("myProp.properties"));
After then for example if you want to read a boolean value from the properties file use
boolean Example = diskReader.nextBoolean();
If you wan't to write to a file it's a bit more complicated but this is how I do it:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class UpdateAFile {
static Random random = new Random();
static int numberValue = random.nextInt(100);
public static void main(String[] args) {
File file = new File("myFile.txt");
BufferedWriter writer = null;
Scanner diskScanner = null;
try {
writer = new BufferedWriter(new FileWriter(file, true));
} catch (IOException e) {
e.printStackTrace();
}
try {
diskScanner = new Scanner(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
appendTo(writer, Integer.valueOf(numberValue).toString());
int otherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(otherValue + 10).toString());
int yetAnotherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(yetAnotherValue * 10).toString());
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void appendTo(BufferedWriter writer, String string) {
try {
writer.write(string);
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And then write to the file by:
diskWriter.write("BlahBlahBlah");
If I want to create a file in C:/a/b/test.txt, can I do something like:
File f = new File("C:/a/b/test.txt");
Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path, Paths, and Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}