I am trying to modify a config file in Java using Properties. I try to modify two of the multiple entries like this:
Properties properties = new Properties();
FileInputStream fin = null;
FileOutputStream fout = null;
fin = new FileInputStream(mCallback.getConfFile());
fout = new FileOutputStream(mCallback.getConfFile());
properties.load(fin);
properties.setProperty(Wrapper.GAME_PATH_KEY, (String)gamePathText.getText());
properties.setProperty(Wrapper.GAME_TYPE_KEY, (String)selectedGame.getSelectedItem());
properties.store(fout, null);
But when I check the file after the result I find out that the whole file was overwritten, leaving only these two entries. This is an android app though I guess it's not relevant to the problem here. What I am doing wrong?
You have to read all properties and then modify the ones you want. After that you have to write all to file. You cannot do only an item modification. The Properties API doesn't provide that functionality to modify.
Edit:
Interchange these two statements-
fout = new FileOutputStream(mCallback.getConfFile());
properties.load(fin);
You should load first before you create a file with the same name.
From Properties:
public void store(OutputStream out,
String comments)
throws IOException
Writes this property list (key and element pairs) in this Properties table to the output > stream in a
format suitable for loading into a Properties table using the
load(InputStream) method.
Properties from the defaults table of this
Properties table (if any) are not written out by this method.
This method outputs the comments, properties keys and values in the
same format as specified in store(Writer), with the following
differences:
So, Load the data first, then set the required data, then store it.
Properties prop =new Properties();
prop.load(new FileInputStream(filename));
prop.setProperty(key, value);
prop.store(new FileOutputStream(filename),null);
The previous poster was kind of right, just not at the right place.
You need to open the FileOutputStream after you've loaded the properties otherwise it clears the file's content.
Properties properties = new Properties();
FileInputStream fin = null;
FileOutputStream fout = null;
fin = new FileInputStream(mCallback.getConfFile());
// if fout was here, the file would be cleared and reading from it would produce no properties
properties.load(fin);
properties.setProperty(Wrapper.GAME_PATH_KEY, (String)gamePathText.getText());
properties.setProperty(Wrapper.GAME_TYPE_KEY, (String)selectedGame.getSelectedItem());
fout = new FileOutputStream(mCallback.getConfFile());
properties.store(fout, null);
Related
The question is rather simple. I am using the aspose library to convert a pdf file to excel. The excel file is subsequently written to the database and this generated excel file is not needed in the future.
My method:
public void main(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
Document document = new Document(inputStream);
ExcelSaveOptions options = new ExcelSaveOptions();
options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);
document.save("newExcelFile.xlsx", options);
}
In this method, the file is saved to the root folder of the project (if it is running locally). How can I not store this file, but make it temporary? My question is that this project is located on the server, and I would not like to create directories specifically for this file.
The Document.save() method has an overload for saving to an OutputStream (See here for the API reference).
Given that you can store the result to anything that implements an OutputStream, you can provide any implementation that you want - one useful option might be to use ByteArrayOutputStream to store the result in memory, or possibly - just use Files.createTempFile() and create a FileOutputStream for that.
For example, your code may be rewritten thus:
public byte[] convertToExcel(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
Document document = new Document(inputStream);
ExcelSaveOptions options = new ExcelSaveOptions();
options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos, options);
return baos.toByteArray();
}
So I have a property file in my project. I need to access it.
Here's the tree structure:
+ Project Name
|--+ folder1
|--+ propertyfolder
|--+ file.properties
Or: Project/propertyfolder/file.properties
Here's what I've tried so far (one at a time, not all at once):
// error: java.io.File.<init>(Unknown Source)
File file = new File(System.getProperty("file.properties"));
File file = new File(System.getProperty("propertyfolder/file.properties"));
File file = new File(System.getProperty("propertyfolder\\file.properties"));
File file = new File(System.getProperty("../../propertyfolder/file.properties"));
And:
InputStream inputStream = getClass().getResourceAsStream("file.properties");
InputStream inputStream = getClass().getResourceAsStream("../../propertyfolder/file.properties");
InputStream inputStream = getClass().getResourceAsStream("propertyfolder/file.properties");
InputStream inputStream = getClass().getResourceAsStream("propertyfolder\\file.properties");
And all variations within getClass(), such as getClass().getClassLoader(), etc.
The error I'm getting is a NullReferenceException. It's not finding the file. How do I find it correctly?
(taken from comment to answer as OP suggested)
Just use File file = new File("propertyfolder/file.properties") but you do need to know where is java process working directory, if you cannot control it try an absolute path /c:/myapp/propertyfolder/file.properties.
You may also use /myapp/propertyfolder/file.properties path without C: disk letter to avoid windows-only mapping. You may use / path separator in Java apps works in Win,Linux,MacOSX. Watch out for text file encoding, use InputStreamReader to given an encoding parameter.
File file = new File("propertyfolder/file.properties");
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader reader = new BufferedReader(isr);
..read...
reader.close(); // this will close underlaying fileinputstream
Inorder to use getClass().resourceAsStream("file.properties") you need to make sure the file is there in the classpath.
That is if your Test.java file is compiled into bin/Test.class then make sure to have file.properties in the bin/ folder along with the Test.class
Otherwise you can use the Absolute Path, which is not advisable.
Did you set System properties to load file.properties from
1) Command line using -Dpropertyname=value OR
2) System.setProperty() API OR
3) System.load(fileName) API?
If you have n't done any one of them, do not use System.getProperty() to load file.properties file.
Assuming that you have not done above three, the best way to create file InputStream is
InputStream inputStream = getClass().getResourceAsStream("<file.properties path from classpath without />");
Properties extends Hashtable so, Each key and its corresponding value in the property list is a string.
Properties props = new Properties();
// File - Reads from Project Folder.
InputStream fileStream = new FileInputStream("applicationPATH.properties");
props.load(fileStream);
// Class Loader - Reades Form src Folder (Stand Alone application)
ClassLoader AppClassLoader = ReadPropertyFile.class.getClassLoader();
props.load(AppClassLoader.getResourceAsStream("classPATH.properties"));
for(String key : props.stringPropertyNames()) {
System.out.format("%s : %s \n", key, props.getProperty(key));
}
// Reads from src folder.
ResourceBundle rb = ResourceBundle.getBundle("resourcePATH");// resourcePATH.properties
Enumeration<String> keys = rb.getKeys();
while(keys.hasMoreElements()){
String key = keys.nextElement();
System.out.format(" %s = %s \n", key, rb.getString(key));
}
// Class Loader - WebApplication : src folder (or) /WEB-INF/classes/
ClassLoader WebappClassLoader = Thread.currentThread().getContextClassLoader();
props.load(WebappClassLoader.getResourceAsStream("webprops.properties"));
To read properties from specific folder. Construct path form ProjectName
InputStream fileStream = new FileInputStream("propertyfolder/file.properties");
If Key:value pairs specified in .txt file then,
public static void readTxtFile_KeyValues() throws IOException{
props.load(new FileReader("keyValue.txt") );
// Display all the values in the form of key value
for (String key : props.stringPropertyNames()) {
String value = props.getProperty(key);
System.out.println("Key = " + key + " \t Value = " + value);
}
props.clear();
}
I Exported my program into a jar file but when I ran it, it seems as if the .properties file isn't found by the program. I made sure it was in the jar file & it worked fine prior to exporting it. I read something about using getClass().getResourceAsStream() instead of FileInputStream and FileOutputStream but can't seem to understand how that would help. Any ideas? These are the two methods that use the file.
private void UpdateData() throws IOException{
FileInputStream in = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("config.properties");
props.setProperty("prop1", prop1TextArea.getText().toString());
props.setProperty("prop2", prop2TextArea.getText().toString());
props.setProperty("prop3", prop3TextArea.getText().toString());
props.store(out, null);
out.close();
}
private void setText() throws IOException {
FileInputStream in = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("config.properties");
prop1TextArea.setText(props.getProperty("prop1"));
prop2TextArea.setText(props.getProperty("prop2"));
prop3TextArea.setText(props.getProperty("prop3"));
out.close();
}
To access resources in your .jar file you have to access them as resources not as files.
The .properties are not in the filesystem anymore and therefore you cannot access them via FileInputStream.
If you want to save them afterwards you have to create new .properties on the first start of your program. So you have to check first if the file exists (e.g. via File.exists()) and either work without the properties from the file or create a new file and use this then.
Sorry if this seems like a newbie question and im sure its just a little thing i need to change but it seems like my program cannot locate the destination for a properties file i coded in.
here is my code
public String metrics() throws IOException {
String result = "";
Properties prop = new Properties();
String propFileName = "C:\\Users\\JChoi\\Desktop\\config.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
if (inputStream == null) {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String Metrics = prop.getProperty("Metrics");
result = Metrics;
System.out.println(result);
return result;
}
I get a nullpointerexception error everytime i run the code but however, when i put the properties file in the resources folder and edit the string name to...
String propFileName = "config.properties";
works fine...any suggestions?
EDIT:
String result = "";
Properties prop = new Properties();
String propFileName = "C:\\Users\\JChoi\\Desktop\\config.properties";
FileInputStream fileInputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(fileInputStream);
SOLVED!
String propFileName = "C:\\Users\\JChoi\\Desktop\\googlebatchfile\\config.properties";
BufferedInputStream inputStream;
FileInputStream fileInputStream = new FileInputStream(propFileName);
inputStream = new BufferedInputStream(fileInputStream);
If you know the full path to a file, then do not try to open it using a classpath search (which is what getResourceAsStream() does).
Instead open the file using an inputsteam that takes a path.
Here is some code:
FileInputStream inputStream = new FileInputStream(propFileName);
The following might be a better technique (I'm not sure with property loading):
BufferedInputStream inputStream;
FileInputStream fileInputStream = new FileInputStream(propFileName);
inputStream = new BufferedInputStream(fileInputStream);
You are attempting to load a file using a classpath-based input stream but specifying a filepath.
This:
getClass().getClassLoader().getResourceAsStream(propFileName);
Will attempt to search the classpath starting at the root (based on whatever the classloader considers the root).
If you want to load a file from outside the classpath, you probably just want to use something like a FileInputStream instead.
So if we do like this:
Properties props = new Properties();
OutputStream osr = new FileOutputStream(Store.class.getResource("my.properties").getFile());
props.setProperty("wallboard_text_rgb", "aaa");
props.setProperty("wallboard_back_rgb", "bbb");
props.store(osr, "");
other keys in existing properties will be deleted, how to avoid that?
Load properties from that file before modifying it. In other words, replace
Properties props = new Properties();
with
Properties props = Properties.load(new FileInputStream(Store.class.getResource("my.properties").getFile()));
The simplest solution is to use
String filename = Store.class.getResource("my.properties").getFile();
OutputStream osr = new FileOutputStream(filename, true); // append.
If you don't want to keep appending to the file, you have to read all the existing values and re-write them. Unfortunately properties don't preserve order, or comments, blanks lines etc.