How can I save a prop file in a specific folder for example,
now it is saved in the root I guess, but it needs to be in the same folder as the class where it is created.
I also want to know how to load it. If it possible to load a properties file easily from the root then it is okay as well to save it in the root.
code creating the file, first 2 lines with // ( = make code work now without using prop file), class name = Providers
public static DataAccessProvider createProvider (URL url) {
//MovieDAOOnline mdaoOn = new MovieDAOOnline();
//mdaoOn.setUrl(url);
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("uri", url.toString());
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new OnlineProvider();
}
code for getting the file, first line in comment needs to be changed to get uri from propertie:
public Movie getMovie(int id) throws DataAccessException{
//StringBuilder builder = new StringBuilder(url.toString());
builder.append("movies.xml");
MovieConfigRead mcr = new MovieConfigRead();
List<Movie> film = null;
try {
film = mcr.geefMovies(builder.toString());
} catch (JAXBException e) {
throw new DataAccessException();
} catch (MalformedURLException e) {
throw new DataAccessException();
}
for (Movie movie : film) {
if (movie.getId() == id) {
return movie;
}
}
return null;
}
Related
Hello all I am having a problem when exporting a named file to the device internal storage for my apps Sqlite database name.
I am getting the error
java.io.FileNotFoundException: /storage/emulated/0/Download/:/09/12/2017-JDO.db: open failed: ENOENT (No such file or directory)
when trying to name the file /09/12/2017-JDO.
I am using File.pathSeparator() with the passed in file name but still am not having any luck. I think it has to do with the / in the file name which is the reason why I tried the File.pathSeparator() to begin with since I want that option for naming the file if the user wants to include the date in that format or in combination with the /.
Here are some code snippets of the methods I am using to try and accomplish this and to show what I am trying to do.
/*
This method saves and exports the current database to the device's internal Downloads folder
This is the default named database
*/
public void backUpDatabase() {
/* Open your local db as the input stream */
DBHelper anotherDbHelper = null;
try {
try {
anotherDbHelper = new DBHelper(ExistingTallyActivity.this);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String path = null;
if (anotherDbHelper != null) {
path = String.valueOf(getApplicationContext().getDatabasePath(anotherDbHelper.getDatabaseName()));
}
File dbFile = null;
if (path != null) {
dbFile = new File(path);
}
FileInputStream fis = null;
try {
if (dbFile != null) {
fis = new FileInputStream(dbFile);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String outFileName = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/Pipe_Tally");
/* Open the empty db as the output stream */
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(outFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/* Transfer bytes from the input-file to the output-file */
byte[] buffer = new byte[1024];
int length;
try {
if (fis != null) {
while ((length = fis.read(buffer)) > 0) {
try {
if (outputStream != null) {
outputStream.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
/* Close the streams */
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (anotherDbHelper != null) {
anotherDbHelper.close();
}
}
/*
This method renames the database to what the user inputs they want. Note: The original db is
still present and stored in the Downloads folder as well.
*/
public void renameDbFile(String desiredDbName) {
/* Open your local db as the input stream */
DBHelper dbHelperToRename = null;
try {
try {
dbHelperToRename = new DBHelper(ExistingTallyActivity.this);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String pathRenamed = null;
if (dbHelperToRename != null) {
pathRenamed = String.valueOf(getApplicationContext().getDatabasePath(dbHelperToRename.getDatabaseName()));
}
File dbFileRenamed = null;
if (pathRenamed != null) {
dbFileRenamed = new File(pathRenamed);
}
FileInputStream fisRenamed = null;
try {
if (dbFileRenamed != null) {
fisRenamed = new FileInputStream(dbFileRenamed);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/* Here is where the db is renamed by the user by inserting the passed in string to the method */
String outFileNameRenamed =
(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath() + "/"+desiredDbName+".db");
// Open the empty db as the output stream
OutputStream outputStreamRenamed = null;
try {
outputStreamRenamed = new FileOutputStream(outFileNameRenamed);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/* Transfer bytes from the input-file to the output-file */
byte[] bufferRenamed = new byte[1024];
int length;
try {
if (fisRenamed != null) {
while ((length = fisRenamed.read(bufferRenamed)) > 0) {
try {
if (outputStreamRenamed != null) {
outputStreamRenamed.write(bufferRenamed, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
/* Close the streams */
try {
if (outputStreamRenamed != null) {
outputStreamRenamed.flush();
outputStreamRenamed.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fisRenamed != null) {
fisRenamed.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (dbHelperToRename != null) {
dbHelperToRename.close();
}
}
/*
This method exports the database into CSV format as well by naming it the passed in string value
for the desired name.
*/
#TargetApi(Build.VERSION_CODES.KITKAT)
public void saveDbAsCsv(String desiredCsvName) {
/* Getting a instance of the DbHelper class right here. */
DBHelper dbhelperCsv = null;
try {
dbhelperCsv = new DBHelper(ExistingTallyActivity.this);
} catch (ClassNotFoundException | NoSuchFieldException e) {
e.printStackTrace();
}
/* Original name of the file dir where the db will be stored in csv format. (Just like SQLite) */
String pathRenamedCsv = null;
if (dbhelperCsv != null) {
pathRenamedCsv = String.valueOf(getApplicationContext().getDatabasePath(dbhelperCsv.getDatabaseName()));
}
/* Creating a File type here with the passed in name from above from the string */
File dbFile = getDatabasePath(pathRenamedCsv);
/*
Appending the desired name to the Downloads Directory here, which is where the new file
will be written
*/
String renamedCsvName = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/"+desiredCsvName);
File exportDir = new File(String.valueOf(renamedCsvName));
if (!exportDir.exists())
{
exportDir.mkdirs();
}
/*
Critical .csv extension here. Took me a while originally to figure out where to pass this
in at. Was at first passing it into the renamedCsvName up above and it was just returning
a folder with the .csv extension and not the file contained withn.
*/
File file = new File(exportDir, desiredCsvName+".csv");
try
{
/* Passing in the string value of the file to an instance of the CsvWriter class */
CsvWriter csvWriter = new CsvWriter(String.valueOf(file));
SQLiteDatabase db = null;
if (dbhelperCsv != null) {
db = dbhelperCsv.getReadableDatabase();
}
/* Getting a cursor from the database table Tally_File */
Cursor curCSV = null;
if (db != null) {
curCSV = db.rawQuery("SELECT * FROM Tally_File",null);
}
if (curCSV != null) {
csvWriter.writeRecord(curCSV.getColumnNames());
}
if (curCSV != null) {
while(curCSV.moveToNext())
{
/* Exporting all the columns here to write out to the csv file */
String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2),
curCSV.getString(3), curCSV.getString(4), curCSV.getString(5),
curCSV.getString(6), curCSV.getString(7), curCSV.getString(8),
curCSV.getString(9), curCSV.getString(10), curCSV.getString(11),
curCSV.getString(12), curCSV.getString(13), curCSV.getString(14), curCSV.getString(15),
curCSV.getString(16)};
/*
Critical here as I was not at first calling the writeRecord that accepted the
String[] array and was calling the toString() method on it and only getting a large
array.
*/
csvWriter.writeRecord(arrStr);
}
}
csvWriter.close();
if (curCSV != null) {
curCSV.close();
}
}
catch(Exception sqlEx)
{
Toast.makeText(this, "Error naming file", Toast.LENGTH_LONG).show();
}
}
Here is where I am calling the methods and passing in the desiredName for naming the file/Db, which is switch case dependent on a menu selection, all within the same activity.
case R.id.menu_save_and_export:
Thread threadMenuSaveAndExport = new Thread();
/*
This method verifies user permissions then calls the backUpDatabase() method to
backup the original db file before the user renames it, if desired.
*/
verifyStoragePermissions(new Runnable() {
#Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
/* Calling this method here to backup the current database*/
backUpDatabase();
}
});
/* Loading the view of activity_database_name with this LayoutInflater*/
View view = LayoutInflater.from(ExistingTallyActivity.this)
.inflate(R.layout.activity_database_name,null);
/*This editText handles the input from the user for their chosen db name*/
mEtCustomDbName = (EditText) view.findViewById(R.id.etCustomDbName);
AlertDialog.Builder alert = new AlertDialog.Builder(ExistingTallyActivity.this);
/* Taken from the strings.xml file. Says Name Database Prior To Export */
alert.setMessage(getResources().getString(R.string.name_your_db));
alert.setView(view);
/* Using the global "Ok" string from strings.xml */
alert.setPositiveButton(getResources().getString(R.string.global_ok_text), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* Passing in the results of the editText to a string here*/
String userDefinedDbName = mEtCustomDbName.getText().toString().trim();
/*
Calling this method to rename the existing db to what the user input
Note: The original db remains in the same folder, as it was previously
backed up from the backUpDatabase() method above. Using the if statement
below to check for a empty string and if it is, the file is not renamed.
Both situations display custom toast message dependent on which executes.
Also implementing the File.separator method to help with File naming
issues on the Android "Unix-like" filesystem
*/
if (userDefinedDbName.length() > 0) {
/* Naming to a .db extension with this method. Works with SQLite */
renameDbFile(File.pathSeparator+userDefinedDbName);
/* Naming to a .csv extension with this method for working with Excel */
saveDbAsCsv(File.pathSeparator+userDefinedDbName);
Toast.makeText(ExistingTallyActivity.this,
/* Using the "Database Saved" string from strings.xml */
getResources().getString(R.string.database_saved),
Toast.LENGTH_LONG).show();
}else {
Toast.makeText(ExistingTallyActivity.this,
/* Using the "Database Not Saved" string from strings.xml */
getResources().getString(R.string.database_not_saved),
Toast.LENGTH_LONG).show();
}
}
});
/* Using the global "Cancel" string from strings.xml */
alert.setNegativeButton(getResources().getString(R.string.global_cancel_text), null);
alert.setCancelable(false);
AlertDialog showAlert = alert.create();
showAlert.show();
threadMenuSaveAndExport.start();
break;
Any advice or help would be greatly appreciated with this as I do want to be able to use the naming with / if desired as an option. Thanks
I have a problem with an exported jar file. When I run my project in Eclipse it runs fine, but when I run it as an exported jar from the console I receive the following error message:
java.io.FileNotFoundException: firstLaunch.properties (System can't find file)
or
java.io.FileNotFoundException: resources/config/firstLaunch.properties (System can't find file)
I tried to put it in to the resource folder and change syntax from firstLaunch.properties to /resource/config/firstLaunch.properties, but again it says the same thing but with a different path. I don't know why is this doing this.
Here is the code:
public void saveConfigFile(String file, String key, String value) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(file);
// set the properties value
prop.setProperty(key, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My syntax for executing the method is
if (properties.loadConfigFile("firstLaunch.properties", "value").equals(properties.loadConfigFile("true.properties", "true"))) {
properties.saveConfigFile("port.properties", "port", "8795");
properties.saveConfigFile("ip.properties", "ip", temp[1]);
properties.saveConfigFile("firstLaunch.properties", "value", "false");
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
} else {
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
}
Your problem probably has to do with how you are referencing the file location. Add some detail/code examples as to how you are referencing the code, so then we can be sure to help. Having said that here is another way to reference a properties file:
Put it in the classpath like this:
private static Properties prop = new Properties();
private static String filename = "<name of file>.properties";
InputStream input = <ClassName>.class.getClassLoader().getResourceAsStream(filename);
try {
if (input==null) {
loggerOut.log(Level.SEVERE, "Sorry, unable to find " + filename);
}
prop.load(input);
loggerOut.info("XML In storage path: " prop.getProperty("<property in file>"));
fileNameAndPath = prop.getProperty("fileNameAndPathIN").trim();
logNameAndPath = logPath + logName;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input!=null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am having a jsp file in which I load the existing values present in properties file. When the user edit the existing value and submit the form, the properties file must be updated with that values. Can anyone help me with this? I am using only java.
FileInputStream in = new FileInputStream("Example.properties");
Properties props = new Properties();
props.load(in);
Now Update it
FileOutputStream outputStream = new FileOutputStream("Example.properties");
props.setProperty("valueTobeUpdate", "new Value");
props.store(outputStream , null);
outputStream .close();
Another way of achieving same is explained at
http://crunchify.com/java-properties-files-how-to-update-config-properties-file-in-java/
PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties");
config.setProperty("Name", "abcd");
config.setProperty("Email", "abcd#gmail.com");
config.setProperty("Phone", "123456");
config.save();
here is an example of how to update your properties file :
public class PropertyManager {
private static Properties prop = new Properties();
private static String PROPERTY_FILENAME = "config.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.get("myProperty"));
updateProperty("myProperty", "aSecondValue");
}
public static void loadProperty(){
InputStream input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(String name, String value){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty(name, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I let you change "new Properties", by the way you retrieve it.
I am creating a properties file and putting into my classpath folder Resources.
When I tried to read this file , i am not getting the expected result. i am getting the result of the previous values printed instead of the property values set now.
My class file is as follows :
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
PrintWriter output = null;
try {
output = new PrintWriter("Resources/config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
if(output!=null) {
System.out.println("Output");
output.close();
}
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
Properties prop1 = new Properties();
BufferedInputStream input = null;
try {
String filename = "config.properties";
input = (BufferedInputStream) AppCPLoad.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop1.load(input);
//get the property value and print it out
System.out.println(prop1.getProperty("database"));
System.out.println(prop1.getProperty("dbuser"));
System.out.println(prop1.getProperty("dbpassword"));
if(input!=null) {
System.out.println("Input");
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Please help.
When you run the program, the properties file is loaded and the values are read. After you rewrite the properties file, that doesn't mean that the properties you have loaded already have be to rewritten. You need to reload the properties file and re-read the values. You are looking for an implementation like ReloadableResourceBundleMessageSource
I'm looking for a place where are objects after serialization ? I would like to put serialized objects(created in another app) to my android project and then only load this files in my game. The problem is that I don't know where do I have to put this objects ? and even if I save object from android app it never saves in my project folder. My load and save functions for objects
public static void save(Context context, Map obj, String nazwa)
{
FileOutputStream str = null;
ObjectOutputStream objStr = null;
try {
str = context.openFileOutput(nazwa, Context.MODE_PRIVATE);
objStr = new ObjectOutputStream(str);
objStr.writeObject(obj);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (objStr != null) objStr.close();
} catch (IOException e) {}
try
{
if (str != null) str.close();
} catch (IOException e) {}
}
}
public static Map load(Context context, String nameFile)
{
Map obj = null;
FileInputStream str_w = null;
ObjectInputStream obj_w = null;
try
{
str_w = context.openFileInput(nameFile);
obj_w = new ObjectInputStream(str_w);
obj = (Map) obj_w.readObject();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
try
{
if (obj_w != null) obj_w.close();
} catch (IOException e) {}
try
{
if (str_w != null) str_w.close();
} catch (IOException e) {}
}
return obj;
}
If I copy my object file to /levels/ and use
final Map map2 = MapManager.load(this, "/levels/map1.lvl");
or
final Map map2 = MapManager.load(this, "levels/map1.lvl");
it never works
How should I do it ?
You're storing them as app private files (Context.MODE_PRIVATE) to a folder only the app has access to, so no other application will be able to access them.
I think the easiest way to store them so they can be shared between apps is to store them to the sdcard using:
Environment.getExternalStorageDir();
Be aware to store them as globally readable.