Android studio, File.properties deleted after reopening the app - java

I saved a File.properties in this.getFilesDir() + "Data.propertie".
In the app, I save the data that the user wrote, but when i open the app, all the data (or the file) that I saves from the previous time has been deleted.
Example:
// Store
for (Map.Entry<String,String> entry : MainActivity.Notes.entrySet()) { // Put all data from Notes in properties to store later
properties.put(entry.getKey(), entry.getValue());
}
try { properties.store(new FileOutputStream(this.getFilesDir() + "data.properties"), null); } // Store the data
catch (IOException e) { e.printStackTrace(); } // Error exception
// Load the map
Properties properties = new Properties(); // Crate properties object to store the data
try {
properties.load(new FileInputStream(this.getFilesDir() + "data.proprties")); } // Try to load the map from the file
catch (IOException e) { e.printStackTrace(); } // Error exception
for (String key : properties.stringPropertyNames()) {
Notes.put(key, properties.get(key).toString()); // Put all data from properties in the Notes map
}
// Can load the data
You can see that i saved the data in the file, and I can load it, but when I open the app, the data has been deleted
There is a way to write in the file and save the data that i write to the next time I open the app?

First off Context.getFilesDir returns a File object. This File represents the private data directory of your app.
Then you do getFilesDir() + "foo" which will implicitly call toString() on the File instance. File.toString() is equivalent to File.getPath which does not necessarily return a trailing slash.
This means, if getFilesDir() returns a File at /data/app, your properties file will become /data/appdata.properties which is not in your data Folder and cannot be written to.
Instead, to get a File within a directory you can create a new File instance with that directory. e.g:
File propertiesFile = new File(this.getFilesDir(), "data.properties");
// use propertiesFile for FileOutputStream/FileInputStream etc.
This ensures that your properties file is within that directory and prevents any issues from file separators

Related

Android Studio write to .properties file

I followed Where to put own properties file in an android project created with Android Studio? and I got an InputStream which reads from my .properties file successfully. However, I can't write to that .properties file, as there is no similar method to getBaseContext().getAssets().open ("app.properties") which returns an OutputStream. I have also read Java Properties File appending new values but this didn't seem to help me, my guess is my file name for the file writer is wrong but I also tried "assets\userInfo.properties" which also doesn't work.
My .properties file is in src\main\assets\userInfo.properties
Properties props = new Properties();
InputStream inputStream = null;
try{
inputStream = getBaseContext().getAssets().open("userInfo.properties");
props.load(inputStream);
props.put("name", "smith");
FileOutputStream output = new FileOutputStream("userInfo.properties"); //this line throws error
props.store(output, "This is overwrite file");
String name = props.getProperty("name");
Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + name);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Current code throws this error:
java.io.FileNotFoundException: userInfo.properties (Read-only file system)
You can't write to the assets folder, as it is inside the APK which is read-only.
Use internal or external storage instead
You can't write to the assets folder. If you want to update your properties file, you'll have to put them some place else. If you want the initial version in the assets or raw folder, just copy it to the default files dir when the app is first used, then read from/write to it there.

java.io.FileNotFoundException when creating FileInputStream

Getting an error when trying to open a FileInputStream to load Map from file with .ser extension.
Constructor where I create new File and invoke method that loads map from file:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("database.ser"); // oddly this does not create a file if one does not exist
loadDB();
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn);
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I've tried to create file manually and put it in same package with class, but it does not help. What's going on?!
Thank You!
You provide a relative path for the file. That means program will look for the file relative to the working directory.
Depending on how you run the program it will be the directory you run it from (if run from Shell/Cmd) or whatever is configured in the project settings (if run from the IDE). For the latter, it depends on the IDE but usually it's the project root directory.
More info on working directory: https://en.wikipedia.org/wiki/Working_directory
More info on relative path: https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths
Regarding creation of the file, it would create non-existing file if you were to write to it. When you read it, it expects it to exist. That means you have to create empty file (if one does not exist) before reading or simply treat exception as empty content.
The path to the file you have given might be wrong for IDE it can take relative path but from the command line, it will take the absolute path.

Properties file reads old data when jar is executed from command line

I have created a java application that copies data from properties file (resources-> settings -> config.properties) and uses it. At one point the properties file values are updated and the code has to use the new values. The code works fine when executed from Netbeans. But when I execute ti from the dist folder after build, the old values get loaded everytime even when I change the the properties file. The properties file gets updated but the values used are still the old ones.
Code to write properties file
File f = new File(System.getProperty("user.dir") + "\\resources\\settings\\config.properties");
try (OutputStream output = new FileOutputStream(f)) {
Properties prop = new Properties();
// set the properties value
prop.setProperty("xml", xmlFileTextBox.getText());
// save properties to project root folder.
prop.store(output, null);
} catch (IOException exception) {
exception.printStackTrace();
}
Code to read values in properties file
try {
Properties prop = new Properties();
String propFileName = "settings/config.properties";
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName)) {
if (inputStream != null) {
prop.load(inputStream);
xmlFileTextBox.setText(prop.getProperty("xml"));
}
inputStream.close();
}
} catch (Exception e) {
System.out.println("Exception: " + e);}
The file you are reading from is a file that is packaged with your application and not the file you are saving to.
This code, getClass().getClassLoader().getResourceAsStream(propFileName)), gives you a resource from the classpath.
You need to create the File in the same way as when you save the properties, then get the InputStream from that File.
If you want to have the defaults in your original properties file you might need to check for null in the "save file" and if it don't have data then read from your default resourse file.

File.createNewFile() failing in java (Ubuntu 12.04)

I am trying to createNewFile() in java.I have written down the following example.I have compiled it but am getting a run time error.
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main(String [] args)
{
try
{
File file = new File("home/karthik/newfile.txt");
if(file.createNewFile())
{
System.out.println("created new fle");
}else
{
System.out.println("could not create a new file");
}
}catch(IOException e )
{
e.printStackTrace();
}
}
}
It is compiling OK.The run time error that I am getting is
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFileExample.main(CreateFileExample.java:16)
some points here
1- as Victor said you are missing the leading slash
2- if your file is created, then every time you invoke this method "File.createNewFile()" will return false
3- your class is very platform dependent (one of the main reasons why Java is powerful programming language is that it is a NON-PLATFORM dependent), instead you can detect a relative location throw using the System.getProperties() :
// get System properties :
java.util.Properties properties = System.getProperties();
// to print all the keys in the properties map <for testing>
properties.list(System.out);
// get Operating System home directory
String home = properties.get("user.home").toString();
// get Operating System separator
String separator = properties.get("file.separator").toString();
// your directory name
String directoryName = "karthik";
// your file name
String fileName = "newfile.txt";
// create your directory Object (wont harm if it is already there ...
// just an additional object on the heap that will cost you some bytes
File dir = new File(home+separator+directoryName);
// create a new directory, will do nothing if directory exists
dir.mkdir();
// create your file Object
File file = new File(dir,fileName);
// the rest of your code
try {
if (file.createNewFile()) {
System.out.println("created new fle");
} else {
System.out.println("could not create a new file");
}
} catch (IOException e) {
e.printStackTrace();
}
this way you will create your file in any home directory on any platform, this worked for my windows operating system, and is expected to work for your Linux or Ubuntu as well
You're missing the leading slash in the file path.
Try this:
File file = new File("/home/karthik/newfile.txt");
That should work!
Actually this error comes when there is no directory "karthik" as in above example and createNewFile() is only to create file not for directory use mkdir() for directory and then createNewFile() for file.

How to upload and save an attachment via XPages Java Bean

I get how you can use Expression Language to bind XPages controls to a Java Bean. Then it accesses the setters and getters automatically.
But how do you handle a file attachment?
What does that look like? I'd like to be able to I guess bind the file upload control to the bean. Save the attachment to "whatever" doc... whether it's the current or external document.. the bean should be able to handle that logic.
I guess I don't know how to get that file attachment into the in memory bean to be able to do anything with it like saving to a document.
any advice would be appreciated.
Update: This is a similar question to this: How to store uploaded file to local file system using xPages upload control?
But in that question the user wants to save to local disc. I'm looking to save to a document.
Thanks!
You need to create a getter and setter in the bean using the com.ibm.xsp.component.UIFileuploadEx.UploadedFile class:
private UploadedFile uploadedFile;
public UploadedFile getFileUpload() {
return uploadedFile;
}
public void setFileUpload( UploadedFile to ) {
this.uploadedFile = to;
}
In the function that processes the bean data (e.g. a save function) you can check if a file was uploaded by checking if the object is null. If it's not null, a file was uploaded.
To process that uploaded file, first get an instance of a com.ibm.xsp.http.IUploadedFile object using the getServerFile() method. That object has a getServerFile() method that returns a File object for the uploaded file. The problem with that object is that it has a cryptic name (probably to deal with multiple people uploading files with the same name at the same time). The original file name can be retrieved using the getClientFileName() method of the IUploadedFile class.
What I then tend to do is to rename the cryptic file to its original file name, process it (embed it in a rich text field or do something else with it) and then rename it back to its original (cryptic) name. This last step is important because only then the file is cleaned up (deleted) after the code is finished.
Here's the sample code for the steps above:
import java.io.File;
import com.ibm.xsp.component.UIFileuploadEx.UploadedFile;
import com.ibm.xsp.http.IUploadedFile;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.RichTextItem;
import com.ibm.xsp.extlib.util.ExtLibUtil; //only used here to get the current db
public void saveMyBean() {
if (uploadedFile != null ) {
//get the uploaded file
IUploadedFile iUploadedFile = uploadedFile.getUploadedFile();
//get the server file (with a cryptic filename)
File serverFile = iUploadedFile.getServerFile();
//get the original filename
String fileName = iUploadedFile.getClientFileName();
File correctedFile = new File( serverFile.getParentFile().getAbsolutePath() + File.separator + fileName );
//rename the file to its original name
boolean success = serverFile.renameTo(correctedFile);
if (success) {
//do whatever you want here with correctedFile
//example of how to embed it in a document:
Database dbCurrent = ExtLibUtil.getCurrentDatabase();
Document doc = dbCurrent.createDocument();
RichTextItem rtFiles = doc.createRichTextItem("files");
rtFiles.embedObject(lotus.domino.EmbeddedObject.EMBED_ATTACHMENT, "", correctedFile.getAbsolutePath(), null);
doc.save();
rtFiles.recycle();
doc.recycle();
//if we're done: rename it back to the original filename, so it gets cleaned up by the server
correctedFile.renameTo( iUploadedFile.getServerFile() );
}
}
}
I have code that processes an uploaded file in Java. The file is uploaded with the normal fileUpload control and then I call the following Java code from a button (that does a full refresh - so that the document including the uploaded file is saved). In the Java code you can do whatever checks you want (filename, filesize etc.):
public void importFile() {
facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
// get a handle an the uploaded file
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String fileUploadID = JSFUtil.findComponent("uploadFile").getClientId(FacesContext.getCurrentInstance());
UploadedFile uploadedFile = ((UploadedFile) request.getParameterMap().get(fileUploadID));
if (uploadedFile == null) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "No file uploaded. Use the file upload button to upload a file.", ""));
return;
}
File file = uploadedFile.getServerFile();
String fileName = uploadedFile.getClientFileName();
// Check that filename ends with .txt
if (!fileName.endsWith(".txt")) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error in uploaded file. The file must end with .txt", ""));
return;
}
try {
// Open the file
BufferedReader br;
br = new BufferedReader(new FileReader(file));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// do stuff with the contents of the file
}
// Close the input stream
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error in uploaded file. Please check format of file and try again", ""));
return;
}
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_INFO, "File successfully uploaded", ""));
}
With a handle on the file object you can store the file in other documents using embedObject.

Categories

Resources