need to extract key from properties file - java

see i have one PROPERTIES File now i have to write a program for extraction of all keys from that file
1000012001 = Title
1000012002 = Status
1000012003 = Start Date
1000012004 = End Date
1000012005 = Date
1000012006 = Name
1000012007 = Description
1000012008 = Sr No
1000012009 = Action
1000012010 = Add
1000012011 = COMPASS Alerts
1000012012 = All
1000012013 = Apply
like in given example i have to extract keys like 100012001---100012013 from that file keys may not be in one sequence and keys need to store in hashmap or arraylist
so please help me

Properties props = new Properties();
props.load(in); // create input stream for your file.
// from now you have Properties object with your data.
// since properties extends Hashtable the task is done.
// if you still need keys in list, say
List<Object> keys = new ArrayList<Object>(props.keySet());
I hope this helps although the question does not seem very clear for me.

You can use java.util.Properties which extends Hashtable.
Properties props=new java.util.Properties();
props.load(inputStream);

Related

best way to store data in Java like pickle

Basically, I just want to save two integeres into a File, so that i can reuse them the next time the programm starts. Id like to do it like pickle in python, beacuse writing it just into a txt file is cumbersome. I have read some articles and other questions wehere they say I should use Java serializatio or XML or JSON, but Im not sure wheter that is the right thing in my case. Id like to use the easiest way.
thank you very much in advance for trying to solve my problem! <3
You could use serialization, XML or JSON (usually with additional libraties). An easy way to store configuration data in files is by using Java property files which are supported by the JRE without any additional dependencies. Property files are text files and have a simple key=value syntax, see below. To write two values to a property file you can do
String prop1 = "foo";
String prop2 = "bar";
try (OutputStream output = new FileOutputStream("config.properties")) {
Properties prop = new Properties();
// set the properties value
prop.setProperty("prop1", prop1);
prop.setProperty("prop2", prop2);
// save properties to project root folder
prop.store(output, "my app's config file");
} catch (IOException io) {
io.printStackTrace();
// TODO: improve error handling
}
which should give you something like
#my app's config file
#Sat Feb 29 12:29:27 CET 2020
prop2=bar
prop1=foo
And to load it:
try (InputStream input = new FileInputStream("config.properties")) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
String prop1 = prop.getProperty("prop1");
String prop2 = prop.getProperty("prop2");
System.out.println("prop1 = " + prop1);
System.out.println("prop2 = " + prop2);
} catch (IOException ex) {
ex.printStackTrace();
// TODO: improve error handling
}
For integer values you would need some type conversion, e.g. the first two lines would be
String prop1 = Integer.toString(23);
String prop2 = Integer.toString(42);
and reading the properties then becomes
int prop1 = Integer.parseInt(prop.getProperty("prop1"));
int prop2 = Integer.parseInt(prop.getProperty("prop2"));
This solution does not scale well in case the number of properties increases or there are frequent changes. For a more generic procedure, see this post: Get int, float, boolean and string from Properties

How to get more than one value from a key in .property

I got a .property file with many user information, I want to get all the users name in a array, but .getProperty only return me the last one, should I use a for each or is there any another way to make it?
prop = new Properties();
prop.load(new FileInputStream("resource/GenLoadFlowEnv.properties"));
String env = (prop.getProperty("ambiente"));
You can simply place
ambiente = a,b,c
And than get the array
String env = (prop.getProperty("ambiente"));
String[] arr = env.split(",");

How to use appProperties in Google Drive api v3?

How to set the app properties of a file using Google Drive v3 in java?
The reference says: "files.update with {'appProperties':{'key':'value'}}", but I don't understand how to apply that to my java code.
I've tried things like
file = service.files().create(body).setFields("id").execute();
Map<String, String> properties = new HashMap<>();
properties.put(DEVICE_ID_KEY, deviceId);
file.setAppProperties(properties);
service.files().update(file.getId(), file).setFields("appProperties").execute();
but then I get an error that "The resource body includes fields which are not directly writable."
And to get the data:
File fileProperty = service.files().get(sFileId).setFields("appProperties").execute();
So how to set and get the properties for the file?
Thanks! :)
Edit
I tried
file = service.files().create(body).setFields("id").execute();
Map<String, String> properties = new HashMap<>();
properties.put(DEVICE_ID_KEY, deviceId);
file.setAppProperties(properties);
service.files().update(file.getId(), file).execute();
but I still get the same error message.
To avoid this error on v3
"The resource body includes fields which are not directly writable."
when calling update, you need to create an empty File with the new changes and pass that to the update function.
I wrote this and other notes as a v3 Migration Guide here.
The Drive API client for Java v3 indicates that the File.setAppProperties will require a Hashmap<String,String> parameter. Try to remove the setFields("appProperties") call since you are trying to overwrite appProperties itself (you're still calling Update at this time).
When retrieving appProperties, you'll just need to call getAppProperties.
Hope this helps!
File fileMetadata = new File();
java.io.File filePath = new java.io.File(YOUR_LOCAL_FILE_PATH);
Map<String, String> map = new HashMap<String, String>();
map.put(YOUR_KEY, YOUR_VALUE); //can be filled with custom String
fileMetadata.setAppProperties(map);
FileContent mediaContent = new FileContent(YOUR_IMPORT_FORMAT, filePath);
File file = service.files().create(fileMetadata, mediaContent)
.setFields("id, appProperties").
.execute();
YOUR_IMPORT_FORMAT, fill this with the value in this link, https://developers.google.com/drive/api/v3/manage-uploads, there is explanation below the example code
setFields("id, appProperties"), fill this with the value in this link: https://developers.google.com/drive/api/v3/migration, this the most important part I think, if you don't set the value in the setFields method your additional input will not be written
With version v3, to add or update appProperties for an existing file and without this error:
"The resource body includes fields which are not directly writable."
You should do:
String fileId = "Your file id key here";
Map<String, String> appPropertiesMap = new HashMap<String, String>();
appPropertiesMap.put("MyKey", "MyValue");
appPropertiesMap.put("MySecondKey", "any value");
//set only the metadata you want to change
//do not set "id" !!! You will have "The resource body includes fields which are not directly writable." error
File fileMetadata = new File();
fileMetadata.setAppProperties(appPropertiesMap);
File updatedFileMetadata = driveService.files().update(fileId, fileMetadata).setFields("id, appProperties").execute();
System.out.printf("Hey, I see my appProperties :-) %s \n", updatedFileMetadata.toPrettyString());

Java: Read Line From File Based on Start of Line

I know how to read from file using Java. What I want to do is read a specific line which starts with specific text.
What I plan on doing is storing certain program settings in a txt file so I can retrieve them quickly when I exit/restart program.
For example, the file may look something like this:
First Name: John
Last Name: Smith
Email: JohnSmith#gmail.com
Password: 123456789
The : would be the delimiter and in the program I want to be able to retrieve specific values based on the "key" (such as "First Name", "Last Name" and so on).
I know I could store it to DB but I want to write it quickly to test my program without going through hassle of writing it to DB.
Have a look at java.util.Properties. It does everything you ask for here, including parsing the file.
example code:
File file = new File("myprops.txt");
Properties properties = new Properties();
try (InputStream in = new FileInputStream (file)) {
properties.load (in);
}
String myValue = (String) properties.get("myKey");
System.out.println (myValue);
Note: if you want to use a space in your property key, you have to escape it. For example:
First\ Name: Stef
Here is documentation about the syntax of the properties file.
What I want to do is read a specific line which starts with specific text.
Read from the start of the file, skipping all the lines you don't need. There is no simpler way. You can index you file for fast access, but you have scan the file at least once.
You can use Properties to retrieve both key and value from file.
Reading data from text file using Properties class
File file = new File("text.txt");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);//with specific key
System.out.println(key + ": " + value);//both key and value
}
You can retrieve specific value based on the key.
System.out.println(properties.getProperty("Password"));//with specific key
With Java 8, you can also read your file into a map this way:
Map<String, String> propertiesMap = Files.lines(Paths.get("test.txt")) // read in to Stream<String>
.map(x -> x.split(":\\s+")) // split to Stream<String[]>
.filter(x->x.length==2) // only accept values which consist of two values
.collect(Collectors.toMap(x -> x[0], x -> x[1])); // create map. first element or array is key, second is value

Setting/Updating multiple document properties in SharePoint 2010 using OpenCMIS

Have tried to search for this almost 'everywhere', but couldn't find a pointer as to how to implement this. Please kindly review my code and offer suggestions on how to set/update ALL documents properties in SharePoint using OpenCMIS. Have created the documents successfully using CMIS, however I'm not able to populate different values for different documents.
For example, a.pdf, b.pdf have different properties. So when I update them, i expect the value to be mapped from array of values assigned to them but at the moment, the same value are being append to all the documents...
Please see my code below, hopefully it will make things clearer:
try {
String [] nextLine =null;
CSVReader reader = new CSVReader(new FileReader(indexFileLocation));
List content = reader.readAll();
for (Object o : content) {
nextLine = (String[]) o;
System.out.println("\n"+ nextLine[2] + "\n"+nextLine[7] + "\n"+ nextLine[6]);
}
//reader.close();
Map <String, Object> newDocProps = new HashMap<String, Object>();
newDocProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
newDocProps.put(PropertyIds.NAME, ff.getName());
Document doc = newFolder.createDocument(newDocProps, contentStream, VersioningState.NONE);
CmisObject cmisobject = (Document) session.getObject(doc.getId());
Map<String, Object> pp = new HashMap<String, Object>();
//pp.put(PropertyIds.OBJECT_ID, "Name");
pp.put("WorkflowNumber", nextLine[7]);
pp.put("InvoiceDate", nextLine[2]);
cmisobject.updateProperties(pp);
Any help is appreciated.
#Albert, How are you creating session? It could be an issue with session creation. Please paste your code here to create session.

Categories

Resources