Using Preferences API to save path? - java

I'm trying use Preferences API to save a path to file in regedit. It is works but the value of path is not saved correctly.
I'm trying this.
public class ImageLogoPreference {
private final String path = "configs";
private Preferences node;
public ImageLogoPreference(){
node = Preferences.userRoot().node(path);
}
public void setImageLogo(){
node.put("logo", "\\IguanaSistemas\\IguanaFight\\imagens\\logo.png");
}
public String getImageLogo(){
String logo = node.get("logo", "image");
return logo;
}
}
At register save this: ///Iguana/Sistemas///Iguana/Fight//imagens//logo.png
Any idea ?

Doesn't matter.
Just get it in your Java program. You don't have a problem.
Preferences node = Preferences.userRoot().node("config");
//node.put("logo", "\\IguanaSistemas\\IguanaFight\\imagens\\logo.png");
String s = node.get("logo", "blah");
System.out.println(s);
Prints the correct string.

Related

Save string/EditText in memory android studio

I have a problem with save the value of string or editText in java android. When I redirect from FirstActivity to Second and return after it to First, I need that a String that i fill earlier stay in the place that I wrote it. (Like a cookies in js).
You could use shared preferences for this process.
In that case, Best practise to create SharedPreference and for global usage, you need to create a global class like below:
public class PreferenceHelper {
private final SharedPreferences mPrefs;
public PreferenceHelperDemo(Context context) {
mPrefs = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 -for private mode
}
private String PREF_Key= "Key";
public String getKey() { // To retrieve data
String str = mPrefs.getString(PREF_Key, null);
return str;
}
public void setKey(String pREF_Key) { // To store and edit Data
Editor mEditor = mPrefs.edit();
mEditor.putString(PREF_Key, pREF_Key);
mEditor.commit();
}
public void clearData(string pREF_Key){ // To delete data
editor.remove(pREF_Key);
editor.commit();
}
}
Then you could use these functions with global class in your activity class to store, retrieve and delete the shared preference data.
Hope this will solve your problem!

Suddenly error ObjectSetting.java file after importing existing project on eclipse

I'm making a Auto SMS sender app on android,
Last time my app is working fine, but suddenly I've to delete the project form my eclipse, for this I wanna again import this project,
After importing this project my app is not working, showing lots of error on Object file.
Please check the screenshot http://prntscr.com/75v2cg
Here is my code
package com.example.serviceexample.model.object;
import java.io.Serializable;
public class ObjectSetting extends Object implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int setting_id;
private String setting_name;
private String setting_value;
public int getSetting_id() {
return setting_id;
}
public void setSetting_id(int setting_id) {
this.setting_id = setting_id;
}
public String getSetting_name() {
return setting_name;
}
public void setSetting_name(String setting_name) {
this.setting_name = setting_name;
}
public String getSetting_value() {
return setting_value;
}
public void setSetting_value(String setting_value) {
this.setting_value = setting_value;
}
public ObjectSetting() {
this.setting_id = 0;
this.setting_name = "";
this.setting_value = "";
}
public ObjectSetting(String name, String value) {
this.setting_id = 0;
this.setting_name = name;
this.setting_value = value;
}
public ObjectSetting(int id, String name, String value) {
this.setting_id = id;
this.setting_name = name;
this.setting_value = value;
}
}
Try setting the java build path . Installed jre needs to be reset in eclipse project properties. As you can see its showing error for java.io and String Class itself .
Frist of all Check your Eclipse preferences. window -> preferences -> Java -> Installed JREs . The installed Jre you're using should be marked there. Also check your project's build path: Right click on the project -> Properties -> Java Build Path. then check in the "libraries" folder whether the JRE System Library is present and if not add it using "Add library"->"JRE System Library" and then select the correct one from an installed JDK (Alternate Jre).

finding the path of file in a Java program

In the following Java program (only showing a part of the whole program)
I have the follwing code:
private final File test_data_file;
private final int algorithm_selection;
private double average_pos_err, average_exe_time;
// The scan list to use for offline
private ArrayList<LogRecord> OfflineScanList;
public OfflineMode(RadioMap RM, File test_data_file, int algorithm_selection, Handler handler) {
this.RM = RM;
this.test_data_file = test_data_file;
this.handler = handler;
this.algorithm_selection = algorithm_selection;
this.OfflineScanList = new ArrayList<LogRecord>();
}
public void run() {
if (!test_data_file.isFile() || !test_data_file.exists() || !test_data_file.canRead()) {
errMsg = test_data_file + " does not exist or is not readable";
handler.sendEmptyMessage(-1);
return;
}
I want to track down, the path of the variable "test_data_file" of type File, but the code does not seems to show me any directions.
do you know where I can find it?
Thank you.
You can use File#getAbsolutePath or File#getCanonicalPath which will resolve the path fully (removing relative components)
using by java 7 you can get file type
String fileType = Files.probeContentType(test_data_file.getPath());
for more detail you can refers
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType%28java.nio.file.Path%29

better way to point to folders and files in a properties file?

I was wondering if there is a better way to have a point to PATH in a properties file. Consider the following code:
public class Properties
{
//MIKE
public final static String PATH_TO_FILE_A = "C:\\programmer_MIKE\fileA.txt";
public final static String PATH_TO_FILE_B = "C:\\programmer_MIKE\fileB.txt";
//BILL
//public final static String PATH_TO_FILE_A = "/Users/BILL/Desktop/fileA.txt";
//public final static String PATH_TO_FILE_B = "/Users/BILL/Desktop/fileB.txt";
}
when any developer need to invoke FILE_A he simply does:
File file = new File(Properties.PATH_TO_FILE_A);
this works ok for BILL if he commented out MIKE's PATH_TO_FILE_A.
Q: is there a better design? If BILL committed his work including the Properties file - he will cause a problem to MIKE (no worries, he'll get a Coffee Latte later on).
the FILES are big (2-4Gb) and we don't want to put them in our repository (svn) and sometimes there are simply temporary folder to create a PDF so we don't want to put them in a "./docs" path.
Thanks for any pointer!
If for whatever reason you really must have hardcoded paths, then you could store them in some kind of map indexed by username. Something like:
public class Properties {
private static Map<String, DeveloperPaths> properties = create();
private static Map<String, DeveloperPaths> create() {
Map<String, DeveloperPaths> properties = new HashMap<String, DeveloperPaths>();
properties.put("mike", new DeveloperPaths(
"C:\\programmer_MIKE\fileA.txt",
"C:\\programmer_MIKE\fileB.txt")
);
properties.put("bill", new DeveloperPaths(
"/Users/BILL/Desktop/fileA.txt",
"/Users/BILL/Desktop/fileB.txt")
);
return properties;
}
public static File FileA()
{
String user = System.getProperty("user.name");
return properties.get(user).fileA;
}
public static File FileB()
{
String user = System.getProperty("user.name");
return properties.get(user).fileB;
}
}
class DeveloperPaths {
public File fileA;
public File fileB;
public DeveloperPaths(String pathA, String pathB) {
fileA = new File(pathA);
fileB = new File(pathB);
}
}
Then, the code to access each path would be identical regardless of developer, for example:
File myFile = Properties.fileA();
Normally paths are configurable entites and should be stored in property file.
Property files has a build in support in java and it uses Properties object for storing that information.
You can read the property file at startup or init (or similar) method of your application and read the proeprties from property file. This will make your configuration dynamic and anyone would be able to change it.
You can create a static method and call it on startup like:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class GetProperties {
public static Properties prop = new Properties();
public static void init() {
InputStream inputStream = GetProperties.class.getClassLoader().getResourceAsStream("application.properties");
try {
prop.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Things like this should be configured externally and/or passed in via parameter, system parameter, or environment variable. Alternatively you could use DI/IoC, but when there's no attached behavior, IMO a config value is plenty.
It's fine to have a hard-coded default, but otherwise stuff like this doesn't belong in code.

Transparent and OS-agnostic path handling in Java

I am developing a graphical installer for our application. Since none of the available installer generators meet the requirements and constraints, I am building it from scratch.
The installer is supposed to run on several operating systems, and therefore the path handling needs to be OS-agnostic. I have written the following small utility for this purpose:
public class Path {
private Path() {
}
public static String join(String... pathElements) {
return ListEnhancer.wrap(Arrays.asList(pathElements)).
mkString(File.separator);
}
public static String concatOsSpecific(String path, String element) {
return path + File.separator + element;
}
public static String concatOsAgnostic(String path, String element) {
return path + "/" + element;
}
public static String makeOsAgnostic(String path) {
return path.replace(File.separator, "/");
}
public static String makeOsSpecific(String path) {
return new File(path).getAbsolutePath();
}
public static String fileName(String path) {
return new File(path).getName();
}
}
Now my code is littered with Path.*Agnostic and Path.*Specific calls in many places. As is apparent, this is very error-prone and not transparent at all.
What approach should I take to make the path handling transparent and less error-prone? Do there exist any utilities/libraries that already address this problem? Any help would be greatly appreciated.
EDIT:
To exemplify what I mean, here is some code I wrote a while ago. (Offtopic: Forgive the long-ish method. The code is in initial stages, and will be undergoing some heavy refactoring soon.)
Some context: ApplicationContext is an object that stores the installation data. That includes several paths such as installationRootDirectory, installationDirectory etc. The defaults for these are specified when creating an installer, and hence are always stored in OS-agnostic formats.
#Override
protected void initializeComponents() {
super.initializeComponents();
choosePathLabel = new JLabel("Please select the installation path:");
final ApplicationContext c = installer.getAppContext();
pathTextField = new JTextField(
Path.makeOsSpecific(c.getInstallationDirectory()));
browseButton = new JButton("Browse",
new ImageIcon("resources/images/browse.png"));
browseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int choice = fileChooser.showOpenDialog(installer);
String selectedInstallationRootDir = fileChooser.getSelectedFile().
getPath();
if (choice == JFileChooser.APPROVE_OPTION) {
c.setInstallationRootDirectory(
Path.makeOsAgnostic(selectedInstallationRootDir));
pathTextField.setText(Path.makeOsSpecific(c.getInstallationDirectory()));
}
}
});
}
Or you could introduce 2 new classes:
class OsSpecificPath implements FilePathInterface
{
String path;
OsAgnosticPath toAgnosticPath();
OsSpecificPath concat( OsSpecificPath otherPath );
// from IFilePath
getFile();
... etc
}
and
class OsAgnosticPath implements FilePathInterface
{
String path;
OsSpecificPath toOsSpecificPath();
OsAgnosticPath concat( OsAgnosticPath otherPath );
// from IFilePath
getFile();
... etc
}
each wrap a path however they need to.
each method could then have methods to convert to the other type of path, but instead of a "stringly-typed" solution where everything is a string and can be misused, you'd have 2 strongly typed classes that can't be incorrectly passed around.
Anything that doesn't care about the type of path would use FilePathInterface, anything that needs to operate on specific kinds of paths would use those types specificly. FilePathInterface could hypothetically have both toAgnosticPath and toOsSpecificPath in the interface if really necessary...
Not sure if this is what you're going for, but usually when I need to do something path-related in an OS-independent Java program, I always use Strings to pass paths around instead of Files, and I always do the following two things:
Whenever I am building a String path, I always use / as the file separator
Whenever I use a String path to create a File or save it as text somewhere, I always make the following calls prior to using the path:
String fSep = System.getProperty("file.separator);
String path = ... //might be built from scratch, might be passed in from somewhere
path = path.replace("/",fSep).replace("\\",fSep);
This seems to work well regardless of whether the path gets built on the local machine or if it gets passed in from a different machine on the network with a different OS, provided that I intend to use the path on the local machine. If you plan to pass the path between different OS'es via networking, just be careful that your own code is consistent.
EDIT
Wow... somehow my answer got mangled up and the code formatting didn't work as initially intended...
You never need to convert back to os-agnostic. here are the conversions to os-specific:
public class Path {
private Path() {
}
public static String concat(String path, String element) {
return new File(path, element).getPath();
}
public static String makeOsSpecific(String path) {
return new File(path).getAbsolutePath();
}
public static String fileName(String path) {
return new File(path).getName();
}
}
Your sample:
#Override
protected void initializeComponents() {
super.initializeComponents();
choosePathLabel = new JLabel("Please select the installation path:");
final ApplicationContext c = installer.getAppContext();
pathTextField = new JTextField(
Path.makeOsSpecific(c.getInstallationDirectory()));
browseButton = new JButton("Browse",
new ImageIcon("resources/images/browse.png"));
browseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int choice = fileChooser.showOpenDialog(installer);
String selectedInstallationRootDir = fileChooser.getSelectedFile().
getPath();
if (choice == JFileChooser.APPROVE_OPTION) {
c.setInstallationRootDirectory(selectedInstallationRootDir);
pathTextField.setText(Path.makeOsSpecific(c.getInstallationDirectory()));
}
}
});
}
I would make my own MyFile object that extends or wraps java.util.File. Then make sure all your code uses this object instead of java.io.File. In here you would be doing the OS checks and calling methods to clean up the file name. The rest of your code would be 'clean'.

Categories