Reading/Writing to Properties Files inside the jar file - java

So i am getting back into writing Java after 4 years so please forgive any "rookie" mistakes.
I need to have a properties file where i can store some simple data for my application. The app data itself won't reside here but i will be storing info such as the file path to the last used data store, other settings, etc.
I managed to connect to the properties file which exists inside the same package as the class file attempting to connect to it and i can read the file but i am having trouble writing back to the file. I am pretty sure that my code works (at least it's not throwing any errors) but the change isn't reflected in the file itself after the app is run in Netbeans.
In the above image you can see the mainProperties.properties file in question and the class attempting to call it (prefManagement.java). So with that in mind here is my code to load the file:
Properties mainFile = new Properties();
try {
mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));
} catch (IOException a) {
System.out.println("Couldn't find/load file!");
}
This works and i can check and confirm the one existing key (defaultXMLPath).
My code to add to this file is:
String confirmKey = "defaultXMLPath2";
String propKey = mainFile.getProperty(confirmKey);
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
try{
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
mainFile.store(fos, "testtest3");
fos.flush();
}catch(FileNotFoundException e ){
System.out.println("Couldn't find/load file3!");
}catch(IOException b){
System.out.println("Couldn't find/load file4!");
}
} else {
// Throw error saying key already exists
System.out.println("Key " + confirmKey + " already exists.");
}
As i mentioned above, everything runs without any errors and i can play around with trying to add the existing key and it throws the expected error. But when trying to add a new key/value pair it doesn't show up in the properties file afterwords. Why?

You should not be trying to write to "files" that exist inside of the jar file. Actually, technically, jar files don't hold files but rather they hold "resources", and for practical purposes, they are read-only. If you need to read and write to a properties file, it should be outside of the jar.

Your code writes to a local file mainProperties.properties the properties.
After you run your part of code, there you will find that a file mainProperties.properties has been created locally.
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
Could order not to confuse the two files you specify the local file to another name. e.g. mainAppProp.properties .
Read the complete contents of the resource mainProperties.properties.
Write all the necessary properties to the local file mainAppProp.properties.
FileOutputStream fos = new FileOutputStream("mainAppProp.properties");
switch if file exists to your local file , if not create the file mainAppProp.properties and write all properties to it.
Test if file mainAppProp.properties exists locally.
Read the properties into a new "probs" variable.
Use only this file from now on.
Under no circumstances you can write the properties back into the .jar file.
Test it like
[...]
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
[...]
Reader reader = null;
try
{
reader = new FileReader( "mainAppProp.properties" );
Properties prop2 = new Properties();
prop2.load( reader );
prop2.list( System.out );
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
if (reader != null) {
reader.close();
}
}
}
[...]
}
output : with prop2.list( System.out );
-- listing properties --
defaultXMLPath2=testtest
content of the file mainAppProp.properties
#testtest3
#Mon Jul 14 14:33:20 BRT 2014
defaultXMLPath2=testtest

Challenge:
Read the Property file location in jar file
Read the Property file
Write the variable as system variables
public static void loadJarCongFile(Class Utilclass )
{
try{
String path= Utilclass.getResource("").getPath();
path=path.substring(6,path.length()-1);
path=path.split("!")[0];
System.out.println(path);
JarFile jarFile = new JarFile(path);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (entry.getName().contains(".properties")) {
System.out.println("Jar File Property File: " + entry.getName());
JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
InputStream input = jarFile.getInputStream(fileEntry);
setSystemvariable(input);
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Jar file"+line);
}
reader.close();
}
}
}
catch (Exception e)
{
System.out.println("Jar file reading Error");
}
}
public static void setSystemvariable(InputStream input)
{
Properties tmp1 = new Properties();
try {
tmp1.load(input);
for (Object element : tmp1.keySet()) {
System.setProperty(element.toString().trim(),
tmp1.getProperty(element.toString().trim()).trim());
}
} catch (IOException e) {
System.out.println("setSystemvariable method failure");
}
}

Related

Trouble writing to file with SMBJ

Please help. I am unable to create and write to a file using SMBJ. I'm getting this error:
com.hierynomus.mssmb2.SMBApiException: STATUS_OBJECT_NAME_NOT_FOUND (0xc0000034): Create failed for <file path>
Is this a Windows errors or an SMBJ error? Am I using the SMBJ API correctly? I don't understand Windows file attributes/options well.
String fileName ="EricTestFile.txt";
String fileContents = "Mary had a little lamb.";
SMBClient client = new SMBClient();
try (Connection connection = client.connect(serverName)) {
AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), domain);
Session session = connection.authenticate(ac);
// Connect to Share
try (DiskShare share = (DiskShare) session.connectShare(sharename)) {
for (FileIdBothDirectoryInformation f : share.list(folderName, "*.*")) {
System.out.println("File : " + f.getFileName());
}
//share.openFile(path, accessMask, attributes, shareAccesses, createDisposition, createOptions)
Set<FileAttributes> fileAttributes = new HashSet<>();
fileAttributes.add(FileAttributes.FILE_ATTRIBUTE_NORMAL);
Set<SMB2CreateOptions> createOptions = new HashSet<>();
createOptions.add(SMB2CreateOptions.FILE_RANDOM_ACCESS);
File f = share.openFile(folderName+"\\"+fileName, new HashSet(Arrays.asList(new AccessMask[]{AccessMask.GENERIC_ALL})), fileAttributes, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OVERWRITE, createOptions);
OutputStream oStream = f.getOutputStream();
oStream.write(fileContents.getBytes());
oStream.flush();
oStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
If the file that you're trying to open does not yet exist, you need to use a different SMB2CreateDisposition. You're now using FILE_OVERWRITE, which is documented as:
Overwrite the file if it already exists; otherwise, fail the operation. MUST NOT be used for a printer object.
You probably want to use FILE_OVERWRITE_IF, which does:
Overwrite the file if it already exists; otherwise, create the file. This value SHOULD NOT be used for a printer object.

How to read from a file not in Eclipse in Java

I have a file which is needed for running tests - this file needs to be personalized (name and password) by whomever is running the test. I do not want to store this file in Eclipse (since it would need to be changed by whomever runs the test; also it would be storing personal info in the repo), so I have it in my home folder (/home/conrad/ssl.properties). How can I point my program to this file?
I've tried:
InputStream sslConfigStream = MyClass.class
.getClassLoader()
.getResourceAsStream("/home/" + name + "/ssl.properties");
I've also tried:
MyClass.class.getClassLoader();
InputStream sslConfigStream = ClassLoader
.getSystemResourceAsStream("/home/" + name + "/ssl.properties");
Both of these give me a RuntimeException because the sslConfigStream is null. Any help is appreciated!
Use a FileInputStream to read data from a file. The constructor takes a string path (or a File object, which encapsulates string path).
Note 1: A "resource" is a file which is in the classpath (alongside your java/class files). Since you don't want to store your file as a resource because you don't want it in your repo, ClassLoader.getSystemResourceAsStream() is not what you want.
Note 2: You should use a cross-platform way of getting a file in a home directory, as follows:
File homeDir = new File(System.getProperty("user.home"));
File propertiesFile = new File(homeDir, "ssl.properties");
InputStream sslConfigStream = new FileInputStream("/home/" + name + "/ssl.properties")
You can simplify your work, using Java's 7 method:
public static void main(String[] args) {
String fileName = "/path/to/your/file/ssl.properties";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also improve your way of reading properties file, using Properties class and forget about reading and parsing your .properties file:
http://www.mkyong.com/java/java-properties-file-examples/
Is this a graphics program (ie. using the Swing library)? If so it is a pretty simple task of using a JFileChooser.
http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html
JFileChooser f = new JFileChooser();
int rval = f.showOpenDialog(this);
if (rval == JFileChooser.APPROVE_OPTION) {
// Do something with file called f
}
You can also use Scanner to read the file.
String fileContent = "";
try {
Scanner scan = new Scanner(
new File( System.getProperty("user.home")+"/ssl.properties" ));
while(scan.hasNextLine()) {
fileContent += scan.nextLine();
}
scan.close();
} catch(FileNotFoundException e) {
}

How to load a properties file from the root directory?

I am currently loading a properties file like this:
private Properties loadProperties(String filename) throws IOException{
InputStream in = ClassLoader.getSystemResourceAsStream(filename);
if (in == null) {
throw new FileNotFoundException(filename + " file not found");
}
Properties props = new Properties();
props.load(in);
in.close();
return props;
}
However, at the moment my file lays at the scr\user.properties path.
But when I want to write to a properties file:
properties.setProperty(username, decryptMD5(password));
try {
properties.store(new FileOutputStream("user.properties"), null);
System.out.println("Wrote to propteries file!" + username + " " + password);
That piece of code generates me a new file at the root folder level of my project.
BUT I want to have one file to write\read.
Therefore how to do that?
PS.: When I want to specify the path I get "Not allowed to modify the file..."
The reason a new file is created because you are trying to create a new file when you are writing. You should first get handle to the user.properties that you want to write to as File object and then try to write to it.
The code would look something along the lines of
properties.setProperty(username, decryptMD5(password));
try{
//get the filename from url class
URL url = ClassLoader.getSystemResource("user.properties");
String fileName = url.getFile();
//write to the file
props.store(new FileWriter(fileName),null);
properties.store();
}catch(Exception e){
e.printStacktrace();
}

How to dynamically add text files in a given directory, in Java?

I am using Eclipse. I want to read number of XML files from a directory. Each XML file contains multiple body tags. I want to extract values of all the body tags. My problem is I have to save each body tag value (text) in a separate .txt file and add these text files in another given directory. Can you plz help how can I create dynamically .txt file and add them in a specified directory?
Thanks in advance.
First specify directory path and name
File dir=new File("Path to base dir");
if(!dir.exists){
dir.mkdir();}
//then generate File name
String fileName="generate required fileName";
File tagFile=new File(dir,fileName+".txt");
if(!tagFile.exists()){
tagFile.createNewFile();
}
add import for java.io.File;
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
replace "myfile.txt" to path to file you needed and file will be created when you say
e.g. "c:\\somedir\\yourfile.txt"
It's not clear why you have mentioned the XML part. But it seems that you are able to get the text from XML file and wanted to write to separate text file.
Please go through this basic tutorial for creating, reading and writing files in Java: http://download.oracle.com/javase/tutorial/essential/io/file.html
Path logfile = ...;
//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();
OutputStream out = null;
try {
out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
...
out.write(data, 0, data.length);
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Do something like this.
try {
//Specify directory
String directory = //TODO....
//Specify filename
String filename= //TODO....
// Create file
FileWriter fstream = new FileWriter(directory+filename+".txt");
BufferedWriter out = new BufferedWriter(fstream);
//insert your xml content here
out.write("your xml content");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
//Close the output stream
out.close();
}

Rename a file using Java

Can we rename a file say test.txt to test1.txt ?
If test1.txt exists will it rename ?
How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for later use?
Copied from http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html
// File (or directory) with old name
File file = new File("oldname");
// File (or directory) with new name
File file2 = new File("newname");
if (file2.exists())
throw new java.io.IOException("file exists");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}
To append to the new file:
java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);
In short:
Files.move(source, source.resolveSibling("newname"));
More detail:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:
Suppose we want to rename a file to "newname", keeping the file in the same directory:
Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));
Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:
Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
You want to utilize the renameTo method on a File object.
First, create a File object to represent the destination. Check to see if that file exists. If it doesn't exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.
If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it's plain text, so I would look at the FileWriter.
For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.
Example:
File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());
The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.
EDIT:
I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.
Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)
String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
File newFile = new File(newFilePath);
try {
FileUtils.moveFile(oldFile, newFile);
} catch (IOException e) {
e.printStackTrace();
}
This is an easy way to rename a file:
File oldfile =new File("test.txt");
File newfile =new File("test1.txt");
if(oldfile.renameTo(newfile)){
System.out.println("File renamed");
}else{
System.out.println("Sorry! the file can't be renamed");
}
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;
Path yourFile = Paths.get("path_to_your_file\text.txt");
Files.move(yourFile, yourFile.resolveSibling("text1.txt"));
To replace an existing file with the name "text1.txt":
Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);
Try This
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
Note :
We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.
Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.
import java.util.Arrays;
import java.util.List;
public class FileRenameUtility {
public static void main(String[] a) {
System.out.println("FileRenameUtility");
FileRenameUtility renameUtility = new FileRenameUtility();
renameUtility.fileRename("c:/Temp");
}
private void fileRename(String folder){
File file = new File(folder);
System.out.println("Reading this "+file.toString());
if(file.isDirectory()){
File[] files = file.listFiles();
List<File> filelist = Arrays.asList(files);
filelist.forEach(f->{
if(!f.isDirectory() && f.getName().startsWith("Old")){
System.out.println(f.getAbsolutePath());
String newName = f.getAbsolutePath().replace("Old","New");
boolean isRenamed = f.renameTo(new File(newName));
if(isRenamed)
System.out.println(String.format("Renamed this file %s to %s",f.getName(),newName));
else
System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
}
});
}
}
}
If it's just renaming the file, you can use File.renameTo().
In the case where you want to append the contents of the second file to the first, take a look at FileOutputStream with the append constructor option or The same thing for FileWriter. You'll need to read the contents of the file to append and write them out using the output stream/writer.
As far as I know, renaming a file will not append its contents to that of an existing file with the target name.
About renaming a file in Java, see the documentation for the renameTo() method in class File.
Files.move(file.toPath(), fileNew.toPath());
works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.
Here is my code to rename multiple files in a folder successfully:
public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
if(newName == null || newName.equals("")) {
System.out.println("New name cannot be null or empty");
return;
}
if(extension == null || extension.equals("")) {
System.out.println("Extension cannot be null or empty");
return;
}
File dir = new File(folderPath);
int i = 1;
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles()) {
try {
File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);
if(f.renameTo(newfile)){
System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
} else {
System.out.println("Rename failed");
}
i++;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and run it for an example:
renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");
I do not like java.io.File.renameTo(...) because sometimes it does not renames the file and you do not know why! It just returns true of false. It does not thrown an exception if it fails.
On the other hand, java.nio.file.Files.move(...) is more useful as it throws an exception when it fails.
Running code is here.
private static void renameFile(File fileName) {
FileOutputStream fileOutputStream =null;
BufferedReader br = null;
FileReader fr = null;
String newFileName = "yourNewFileName"
try {
fileOutputStream = new FileOutputStream(newFileName);
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
fileOutputStream.write(("\n"+sCurrentLine).getBytes());
}
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Categories