So, my I have a method that saves some data in a properties file but something weird happens. See, lets say I have the JAR file on desktop. If I open it directly from there (double click, etc) the properties file is saved in the desktop, as should be. However, if you drag the JAR to the Windows start list and open it from there, the properties file will be saved in the System32 folder.
Here is the method:
private void saveAncientsData() {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("ancients.data");
File file = new File("ancients.data");
// set the properties value
for (int x = 0; x < currentLvlSpinnerFields.size(); x++) {
prop.setProperty(ancientNames[x], currentLvlSpinnerFields.get(ancientNames[x]).getValue().toString());
}
// save properties to project root folder
prop.store(output, null);
JOptionPane.showMessageDialog(this, "Data successfully saved in \n\n" + file.getCanonicalPath(), "Saved", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Would appreciate any help, since I am clueless.
Thanks in advance!
according to your code you haven't give path of property file to create in desktop.
output = new FileOutputStream("ancients.data");
so your property file will be created in same directory where your jar file exists .
but if you run this .jar file from a parent process your jar file created in the directory where that parent process exists.
i guess when windows starts a specific process exist in win32 directory execute start-up programs .i think it's userinit.exe . so your prop file will be created in System32 directory .
if you want property file to create in desktop you can put your jar file in desktop and add a shortcut to .jar or you can give full-path to your desktop like
output = new FileOutputStream(System.getProperty("user.home") + "/Desktop/"+"ancients.data");
edit
to understand this problem
1) create a folder named example in desktop.and then create 2 folders path1 and path2 .then add .jar to path1 folder
2) double click jar in path1 .and a property file will be created in path1 as you expected .
3) delete property file.open command prompt in path2 . To run Prop.jar file in path1 . type call "pathtodesktop/example/path1/Prop.jar" hit enter.
.property file will be created in path2 instead of path1 that's what happening in your case.
Related
I am trying to place a file into SFTP directory using JSch.
channelSftp.cd(destDir);
channelSftp.put(new FileInputStream(filePath), filePath.substring(filePath.lastIndexOf(File.separatorChar)));
But the above code is placing the file always in the SFTP user home directory instead of destDir. For example, if I create a subdirectory test under user home directory and set destDir as channelSftp.getHome()+"test", still the file is being copies to user home directory only instead of test sub-directory.
I tried to list files in destDir (test sub-directory), it is showing all files/directories under test directory.
Vector<com.jcraft.jsch.ChannelSftp.LsEntry> vv = channelSftp.ls(destDir);
if(vv != null) {
for(int ii=0; ii<vv.size(); ii++){
Object obj=vv.elementAt(ii);
if(obj instanceof LsEntry){
System.out.println(((LsEntry)obj).getLongname());
}
}
}
Any suggestions? I looked at permissions (test sub-directory has exactly same permissions as SFTP user home directory).
filePath.substring(filePath.lastIndexOf(File.separatorChar)) result includes even the last separator.
So if you pass /home/user/file.txt, you get /file.txt. That is an absolute path, so any working directory is disregarded and you effectively always write to a root folder.
You want filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1) to get only file.txt.
See also How do I get the file name from a String containing the Absolute file path?
This works for very well !!
channel.connect();
try {
channel.mkdir("subdir");
} catch (Exception e) {
// ... do something if subdir already exists
}
// Then the trick !
channel.put(inputStream, "subdir" + "/" + "filename.ext");
I have a properties file located in C:/codebase/myProject-Authentication/sample.properties, and my workspace is at C:/codebase/myProject/com.company.team.website/src/.../AccessCodeServlet.java.
So, I need to read sample.properties from AccessCodeServlet.java. AccessCodeServlet is a servlet.
If the properties file is in the same folder as AccessCodeServlet.java, I can just do this:
ResourceBundle bundle = ResourceBundle.getBundle("sample");
But how do I do it when properties file is outside workspace?
Well, you can add an external folder containing your sample.properties to the classpath in eclipse:
Open Run Configuration
Select <Your app entry>
Go to "Classpath" tab
Select "User entries"
Click "Advanced" button
Check "Add external folder"
Click "OK" button
Select your external folder with .properties file(s)
Viola - now resource bundles are found!
Move the file to a relative path to the workspace before usage?
public void MovePropertiesFile()
{
InputStream otherStream = null;
OutputStream workspaceStream = null;
try{
File afile =new File("C:\\somwhere\\.....\\properties.properties");
File bfile =new File("C:\\workspace\\.....\\properties.properties");
otherStream = new FileInputStream(afile);
workspaceStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
while ((length = otherStream .read(buffer)) > 0){
workspaceStream .write(buffer, 0, length);
}
otherStream .close();
workspaceStream .close();
}catch(IOException e){
e.printStackTrace();
}
}
You need to specify absolute path but you shouldn't hard-code it as you correctly surmised.
You should get the base path of the file(s) from a System property which you can access using System.getProperty("basePath") in your code and which should be prepended to your file name to create an absolute path.
While running your application you can specify the path in java command line as follows:
java -DbasePath="/a/b/c" ...
... signifies the current arguments to your Java command to run your program.
I have a java project this project has a text file to read from. i want to export a excuteable jar file .
i did it but when i run the program on cmd window it says that the file couldnt be found.
How to export the whole project inclusive the text file ? or should i place the file in another place
scn = new Scanner(new File("src/test.txt"));
while(scn.hasNext())
{
String instructionLine = scn.next();
li.add(instructionLine) ;
}
scn.close();
}
catch(Exception e)
{
System.out.print("File couldnt found !");
}
You need to use getResourceAsStream() to get data from within your jar file.
See this "prior answer on StackOverflow".
I am stuck up in a odd situation that is I am creating a file in a folder but I need to make sure that before the creation of a file if any file is there in the folder then it must be deleted only the current file which is process should be there.
since in my application every day a job runs which create the file in that folder so when ever presently job is running it should delete previous day file and no file should be there in afolder but the code that is shown below creates the file in that folder but the issue is that previous day file or if the job run multiple time on the same day also then those files are also thhere in the folder which should be deleted please advise how to achieve this..
File file = new File(FilePath + s); //path is c:\\abc folder & s is file name fgty.dat file
if (file.exists()) {
file.delete();
}
file.createNewFile();
Please advise
In your place I'd move the directory to a different name, say abc.OLD, recreate it and then create your file. If everything goes well, at the end you can remove the ols directory.
If different instances of your program could be running at the same time you need to implement some form of synchronization. A rather simplistic approach could be to check if the abc.OLD directory exists and abort execution if it does.
Without seeing more of your code, it sounds like you just need to empty the folder before opening a new file, since right now you're only deleting the file with the exact name that you're going to write. Use the list method of file objects.
File newFile = new File(FilePath + s);
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
f.delete();
}
newFile.createNewFile();
Note that this won't work if your folder contains other non-empty directories; you'll need a more robust solution. But the code above will at least delete all the files in the folder (barring Exceptions obviously) before creating the new file.
If, as you mentioned in the comments, you only want to delete *.dat files, it's as simple as putting a check in before you delete anything.
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
if (f.getName().endsWith(".dat")) { // Only delete .dat files
f.delete();
}
}
File file = new File(FilePath+"test.txt");
File folder = new File(FilePath);
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
listOfFiles[i].delete();
}
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
First I think you can have problems with the way you instanciate your Fileobject because if you don't have your path separator (\), you will try to create c:\abcfgty.dat instead of c:\abc\fgty.dat.
Use instead :
File file = new File(filePath, s);
Then you can delete the files ending by ".dat". As I understood, you don't need to delete sub directories. (Here is a link that tells you how. See also here)
for (File f : filePath.list()) { // For each file in the directory, delete it.
if(f.isFile() && file.getName().toLowerCase().endsWith(".dat");){
f.delete();
}
}
try {
file.createNewFile();
} catch (IOException ex) {
//Please do something here, at leat ex.printStackTrace()
}
Note that we can use a FileFilter to select the files to delete.
EDIT
As it was suggested in other answers, it might be preferable to move or rename the existing files instead of deleting them directly.
public xFbConfigReader()
{
//props = new Properties();
propsdatabase = new Properties();
try
{
// load a properties file
InputStream dbin = getClass().getResourceAsStream("/properties/database.properties");
propsdatabase.load(dbin);
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
I keep My properties File named 'Database.properties' in a folder where the project is named 'Properties'.
When I do a Export as jar in Eclipse . The Properties Folder is visible.
But When I run the program it shows that there is a NUll point exception in dbin.
So which means I require the proper way to form a jar in Eclipse .Kindly suggest.
The better solution while handling properties file would be reading
static Properties databaseproperties= new Properties();
static {
try {
connectionProps.load(YourClassName.class.getClassLoader()
.getResourceAsStream("databaseproperties.properties"));
} catch (Exception e) {
System.out.println("Exception is " + e.getMessage());
}
}
This is better approch because
we can move our properties file to someother folder.
And infact we can keep properties folder out side of jar. say you can create
a folder called Configuration where you can include all the
properties files. As it is out side of jar you can change the
properties file when ever is required.
For change in properties
file no need to unjar it.
(OR) simply you can make this change no need to think about directory structure
Step 1: Move properties file to SRC
step 2: change this line as
follows
InputStream dbin = getClass().getResourceAsStream("/database.properties");
This is not much different from previous code as it is anyway stays inside the JAR file.
you are getting null pointer exception because properties file is not loaded try to use
FileInputStream to load the properties as follows
FileInputStream dbin = new FileInputStream("/properties/database.properties");
properties.load(dbin);