I would love to know how can I save and load my HashMap from a file called data.txt , I'm already using a method to save and load the HashMap from a config.yml (which i will show you below).
Here is my HashMap
HashMap<String, Integer> points = new HashMap<String, Integer>();
This is my saving method for the HashMap from the config.yml
public void savePoints(){
for (Entry<String, Integer> pointstostore : points.entrySet()) {
getConfig().set(pointstostore.getKey(), pointstostore.getValue());
}
saveConfig();
}
This is my loading method for the HashMap from the config.yml
public void loadPoints(){
for (String str : getConfig().getKeys(true)) {
int p = getConfig().getInt(str);
points.put(str, p);
}
}
The config.yml is structured like that in a yaml format
playername: points
playername2: points
...
Is there any way for me to create a new file called data.txt from which I can save and load the HashMap points for every player and request from each player the amount of points they have and the file to have the following or a similar format
players:
points:
playername: points
playername2: points
...
Do it by using a Properties.
To write:
Properties p = new Properties();
p.putAll(points):
try (FileOutputStream fos = new FileOutputStream("file.txt");) {
p.store(fos, null);
}
To read:
Properties p = new Properties();
try (FileInputStream fos = new FileInputStream("file.txt");) {
p.load(fos);
points = new Hasmap<>(p);
}
To make a new .yml file you do:
public class Main {
private File datafile;
private FileConfiguration data;
public void onEnable() {
datafile = new File(getDataFolder(), "data.yml");
data = YamlConfiguration.loadConfiguration(datafile);
saveDataYml();
}
public static void saveDataYml() {
try{
data.save(datafile);
}catch(Exception e){
e.printStackTrace();
}
}
public static FileConfiguration getDataYml() {
return data;
}
}
Related
I'm trying to load a json file, convert it into a ConcurrentHashMap and then write into a csv file with the following code:
My json file is of the form
{"lemmas":{"doc4":"which might make it go wrong","doc3":"and no dirty datum","doc2":"each of vary length","doc1":"you should find that it have five line","doc0":"this be a simple text file"}}
package pipeline;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import helpers.JSONIOHelper;
public class DescriptiveStatistics {
private static void StartCreatingStatistics(String filePath) {
System.out.println("Loading file...");
JSONIOHelper JSONIO = new JSONIOHelper(); // create an object of the JSONIOHelper class
JSONIO.LoadJSON(filePath); // call the LoadJSON method
ConcurrentHashMap<String, String> lemmas = JSONIO.GetLemmasFromJSONStructure();
lemmas.forEach((k, v) -> System.out.printf(" %s%n", v));
CountWordsInCorpus(lemmas); // call this method from the end of the StartCreatingStatistics()
}
private static ConcurrentHashMap<String, Integer> CountWordsInCorpus(ConcurrentHashMap<String, String> lemmas) {
// compile the words in the corpus into a list
ArrayList<String> corpus = new ArrayList<String>();
// store the words together with their frequencies
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<String, Integer>();
for (Entry<String, String> entry : lemmas.entrySet()) {
for (String word : entry.getValue().split(" ")) {
corpus.add(word);
}
}
// getting words and their frequencies
for (String word : corpus) {
if (counts.containsKey(word)) {
counts.put(word, counts.get(word) + 1);
} else {
counts.put(word, 1);
}
}
return counts;
}
// writing into a csv file
private void OutputCountsAsCSV(ConcurrentHashMap<String, Integer> counts, String filename) {
String CSVOutput = new String("");
for (Entry<String, Integer> entry : counts.entrySet()) {
String rowText = String.format("%s,%d\n", entry.getKey(), entry.getValue());
System.out.println(rowText);
CSVOutput += rowText;
System.out.println(CSVOutput);
{
try (FileWriter writer = new FileWriter(filename)) {
writer.write(CSVOutput);
System.out.println("CSV File saved successfully...");
}
catch (Exception e)
{
System.out.println("Saving CSV to file failed...");
}
}
}
}
I now want to call the OutputCountsAsCSV() method to pass the csv file name to it, say 'my_file.csv'.
I am not sure how to do it in the main(String[] args) method.
It is easy to call StartCreatingStatistics(), for example, because there is only one argument, but OutputCountsAsCSV() has two arguments and I do not know how to pass ‘counts’ from ConcurrentHashMap<String, Integer> CountWordsInCorpus() to it as the first argument?
public static void main(String[] args) {
String filePath = "JSON_simple.json";
DescriptiveStatistics newobj = new
DescriptiveStatistics();
newobj.StartCreatingStatistics(filePath);
...
// ConcurrentHashMap<String, Integer> newhashmap =
//newobj.CountWordsInCorpus()
String filename = "my_file.csv";
OutputCountsAsCSV ( newhashmap, filename);
}
So if I try 'ConcurrentHashMap<String, Integer> newhashmap = newobj.CountWordsInCorpus()'; it of course, gives an error 'the method CountWordsInCorpus(ConcurrentHashMap<String, String>)' in the type BDescriptiveStatistics is not applicable for the arguments()'.
how can I do it please?
ConcurrentHashMap<String, Integer> newhashmap = newobj.CountWordsInCorpus()
This line is fine; but it back. Except, the CountWordsInCorpus method has an argument: lemmas. You need to find these lemmas someplace and pass them to this method. Your StartCreatingStatistics method does this, but it calls CountWordsInCorpus, and tosses the result in the garbage.
Perhaps StartCreatingStatistics should return it instead. Now your main can call StartCreatingStatistics, save what it returns, and pass that to OutputCountsAsCSV.
I have created a properties file called myproperties.properties as:
test.value1=one
test.value2=two
My java code to read this file is the following:
String test = Utility.getInstance().getProperty("test.value1");
where class Utility is so defined:
public class Utility {
private static Utility _instance = null;
private static Properties properties = new Properties();
static public Utility getInstance(){
if (_instance == null) {
_instance = new Utility();
}
return _instance;
}
private Utility(){
loadUtility();
}
public String getProperty(String tgtPropertyName) {
Object prop = properties.get(tgtPropertyName);
if (prop != null) {
return prop.toString();
} else {
return null;
}
}
private void loadUtility(){
String filename = null;
try{
filename = getClass().getClassLoader().getResource("myproperties").getFile();
InputStream file = new FileInputStream(new File(filename));
properties.load(file);
Iterator iter = properties.keySet().iterator();
while (iter.hasNext()){
System.out.println("FILE LOADED");
}
}catch(Exception e){
}
}
}
This code works correctly. Now I must add a concatenation in my properties file:
test.value3=${test.value1}${test.value2}
and this not worked because my Java code cannot interpret ${}.
The exception is:
Caused by: java.lang.IllegalStateException: Stream handler unavailable due to: For input string: "${test.value1}"
Why?
Use below code to concatenate in type.value3 in properties file
Properties prop=null;
public FileReader FileLoader() throws FileNotFoundException
{
File file=new File("myproperties.properties");
FileReader fileReader=new FileReader(file);
return fileReader;
}
public String propertyLoader(String key) throws IOException
{
FileReader fileReader=FileLoader();
prop=new Properties();
prop.load(fileReader);
String value=prop.getProperty(key);
return value;
}
public void resultWriter() throws IOException
{
String value1=propertyLoader("test.value1");
String value2=propertyLoader("test.value2");
String res=value1+value2;
System.out.println(res);
FileWriter fw=new FileWriter("myproperties.properties");
prop=new Properties();
prop.setProperty("test.value3", res);
prop.store(fw, null);
}
public static void main(String[] args) throws IOException
{
UtilityNew util=new UtilityNew();
util.resultWriter();
System.out.println("Success");
}
Nested properties are not supported in core Java. The only thing you can do is create a class that is going to resolve the ${XXX} values once you have loaded the file.properties into a Properties object.
Or maybe the typesafe library can be usefull to you. https://github.com/lightbend/config. It has a lot of functionalities and one of them is substitutions:
substitutions ("foo" : ${bar}, "foo" : Hello ${who})
But you won't have a key-value properties file anymore, it will look more like a json file.
This might be a late answer but someone might find this useful.
You can write a small utility function which reads the property values and then iteratively replaces any nested values that are present
First search for your pattern. Replace it with the actual value by looking-up at the properties. Repeat this until you get the final string.
Properties properties = new Properties();
properties.setProperty("base_url", "http://base");
properties.setProperty("subs_url", "${base_url}/subs");
properties.setProperty("app_download", "apps/download");
properties.setProperty("subs_detail", "${subs_url}/detail/${app_download}");
String input = properties.getProperty("subs_detail");
Pattern pattern = Pattern.compile("\\$\\{.*?\\}"); //change the pattern here to find nested values
while (pattern.matcher(input).find())
{
Matcher match = pattern.matcher(input);
while (match.find())
{
input = input.replace(match.group(), properties.getProperty(match.group().substring(2, match.group().length()-1)));
}
}
System.out.println("final String : " + input); // this prints http://base/subs/detail/apps/download
I want to create a class that wraps Properties and specifically hides the file I/O operations. I have come up with the abridged code below. This is intended to read the properties from a file at a fixed location outside of the class path. It also has a method to write the properties to the same file.
//
/* Defines key properties of the iFlag application.
* Methods read and write properties.
*/
public class ClientProperties {
private Properties props;
private static String xPanelSizeStg = "32";
private static int xPanelSize = 32;
private static String configFilename = "/home/myname/config/client_config.properties";
public ClientProperties() {
props = new Properties();
}
/**
* Reads properties from file
* Reads the current properties object from file.
* The file is stored in /home/mimibox/config/flag_config.properties
*/
public Properties readPropertiesFromFile( ){
// create and load default properties
InputStream input = null;
logger.trace("Read flag config properties.");
try {
input = new FileInputStream( configFilename );
//load a properties file from class path, inside static method
props.load(input);
//get the property values and save
xPanelSizeStg = props.getProperty("xPanelsize","32");
yPanelSizeStg = props.getProperty("yPanelsize", "32");
}
catch (IOException ex) {
logger.error("Could not open config file" + configFilename,ex );
}
finally{
if(input!=null){
try {
input.close();
}
catch (IOException e) {
logger.error( "Could not close config file" + configFilename,e );
}
}
}
return props;
}
/**
* Writes properties to file
* Writes the current properties object to file.
* The file is stored in /home/mimibox/config/flag_config.properties
*/
public void writePropertiesToFile() {
//saves the current properties to file. Overwrites the existing properties.
Properties props = new Properties(); //a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
System.out.println("Panel size x = " + xPanelSizeStg );
try {
outStrm = new FileOutputStream( configFilename );
// set the properties values
props.setProperty("xPanelsize", xPanelSizeStg);
props.setProperty("yPanelsize", yPanelSizeStg);
// save properties to file, include a header comment
props.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error( "The file :{0} could not be opened", configFilename,io);
} finally {
if (outStrm!= null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
}
The read and write methods work. What doesn't work is trying to change the value of a property, and then save it. The demo code below successfully reads the properties file and displays the correct value for XPanelsize.
I then change that value and attempt to write the properties to a file. The new value 64 for xPanelsize is not written to the file.
public static void main(String[] args) {
Properties props;
ClientProperties p = new ClientProperties();
props = p.readPropertiesFromFile();
String txt = props.getProperty("xPanelsize");
System.out.println("Panel size x = " + txt );
p.setProperty("xPanelsize","64"); //method not found error
p.writePropertiesToFile();
So I would like to be able to use the Property.setProperty() method to set the value of a property. When I do that, the changed property is not written to the file. I can see that is because I have more than 1 Property instance and one is not visible to the other. I think I need to extend the built-in Properties class to achieve what I want to do, but I am not sure how to make it all work.
I have found plenty of examples of using Properties on the internet. What I haven't found are any examples that hide the related file I/O in a class. How would I do that??
OK so thanks to the comments and answers above, I have made a number of changes. For the benefit of those that stumble upon this post, I have posted the working code in this answer. The main change is to extend Properties. This allows me to use the Properties methods directly.
package com.test;
import java.util.Properties;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
public class ClientProperties extends Properties {
//initiate logger
private final static Logger logger = LogManager.getLogger();
private static String xPanelSizeStg = "32";
private static String yPanelSizeStg = "32";
private final configFilename = "/home/myname/myConfig.properties";
public ClientProperties() {
}
public Properties readPropertiesFromFile( ){
// create and load default properties
InputStream input = null;
logger.trace("Read flag config properties.");
try {
input = new FileInputStream( configFilename );
//load a properties file from class path, inside static method
this.load(input);
//get the property values and save
xPanelSizeStg = this.getProperty("xPanelsize","32");
yPanelSizeStg = this.getProperty("yPanelsize", "32");
}
catch (IOException ex) {
logger.error("Could not open config file" + configFilename,ex );
}
finally{
if(input!=null){
try {
input.close();
}
catch (IOException e) {
logger.error( "Could not close config file" + configFilename,e );
}
}
}
return this;
}
public void writePropertiesToFile() {
//saves the current properties to file. Overwrites the existing properties.
//Properties props = new Properties(); //a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
System.out.println("Panel size x = " + xPanelSizeStg );
try {
outStrm = new FileOutputStream( configFilename );
// save properties to file, include a header comment
this.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error( "The file :{0} could not be opened", configFilename,io);
} finally {
if (outStrm!= null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
}
I have relied on the Properties parent to initiate Properties which I have accessed with "this". So now main looks like:
public static void main(String[] args) {
ClientProperties p = new ClientProperties();
p.readPropertiesFromFile();
String txt = p.getProperty("xPanelsize");
System.out.println("Panel size x = " + txt );
p.setProperty("xPanelsize","64");
p.writePropertiesToFile();
}
The class now hides all the admin around reading, writing and files. Crucially it avoids writing a setter/getter for each property (and I have a lot more properties than the two shown here). That is what I had in my first version.
Thanks for your help. It would have taken me a long time to figure all this out by myself.
You should probably need to create a getter for your 'props' object.
public Properties getProps()
{
return props;
}
And you will be able to invoke it like this:
p.getProps().setProperty("key", "value");
Or, if you are planning to make your ClientProperties class a children of Properties class, then you will need to use 'extends' and you would be able to invoke it by using
p.setProperty("key", "value");
And in this case you wouldn't need any Properties object in your class' fields.
This is my suggestion for your example.
First, you don't need to be edit again the properties in your writePropertiesToFile method like this:
public void writePropertiesToFile() {
// saves the current properties to file. Overwrites the existing properties.
// Properties props = new Properties(); // a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
logger.debug("Panel size x = " + xPanelSizeStg);
try {
outStrm = new FileOutputStream(configFilename);
// set the properties values
//props.setProperty("xPanelsize", xPanelSizeStg);
//props.setProperty("yPanelsize", yPanelSizeStg);
// save properties to file, include a header comment
props.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error("The file :{0} could not be opened", configFilename, io);
} finally {
if (outStrm != null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
Then, you just create a setProperty method using the global variable -props- in the class.
private void setProperty(String key, String value) {
this.props.setProperty(key, value);
}
If your property file looks like image below:
The value of xPanelsize should be changed after running application.
public static void main(String[] args) {
Properties props = null;
ClientProperties p = new ClientProperties();
props = p.readPropertiesFromFile();
String xPanelsize = props.getProperty("xPanelsize");
System.out.println("Panel size x = " + xPanelsize);
p.setProperty("xPanelsize", "64"); // method not found error
p.writePropertiesToFile();
props = p.readPropertiesFromFile();
xPanelsize = props.getProperty("xPanelsize");
System.out.println("So, now the Panel size x = " + xPanelsize);
}
The debug message is,
The property file contents will be:
Here is full source:
package stackoverflow;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/* Defines key properties of the iFlag application.
* Methods read and write properties.
*/
public class ClientProperties {
Logger logger = LoggerFactory.getLogger(ClientProperties.class.getSimpleName());
private Properties props;
private String xPanelSizeStg;
private String yPanelSizeStg;
private int xPanelSize;
private int yPanelSize;
// private static String configFilename =
// "/home/myname/config/client_config.properties";
private static String configFilename = "resource/client_config.properties";
public ClientProperties() {
props = new Properties();
xPanelSizeStg = "32";
yPanelSizeStg = "32";
xPanelSize = 32;
yPanelSize = 32;
}
/**
* Reads properties from file Reads the current properties object from file. The
* file is stored in /home/mimibox/config/flag_config.properties
*/
public Properties readPropertiesFromFile() {
// create and load default properties
InputStream input = null;
logger.trace("Read flag config properties.");
try {
input = new FileInputStream(configFilename);
// load a properties file from class path, inside static method
props.load(input);
// get the property values and save
xPanelSizeStg = props.getProperty("xPanelsize", "32");
yPanelSizeStg = props.getProperty("yPanelsize", "32");
} catch (IOException ex) {
logger.error("Could not open config file" + configFilename, ex);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
logger.error("Could not close config file" + configFilename, e);
}
}
}
return props;
}
/**
* Writes properties to file Writes the current properties object to file. The
* file is stored in /home/mimibox/config/flag_config.properties
*/
public void writePropertiesToFile() {
// saves the current properties to file. Overwrites the existing properties.
// Properties props = new Properties(); // a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
logger.debug("Panel size x = " + xPanelSizeStg);
try {
outStrm = new FileOutputStream(configFilename);
// set the properties values
//props.setProperty("xPanelsize", xPanelSizeStg);
//props.setProperty("yPanelsize", yPanelSizeStg);
// save properties to file, include a header comment
props.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error("The file :{0} could not be opened", configFilename, io);
} finally {
if (outStrm != null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
private void setProperty(String key, String value) {
this.props.setProperty(key, value);
}
public int getxPanelSize() {
return this.xPanelSize;
}
public void setxPanelSize(int xPanelSize) {
this.xPanelSize = xPanelSize;
}
public int getyPanelSize() {
return yPanelSize;
}
public void setyPanelSize(int yPanelSize) {
this.yPanelSize = yPanelSize;
}
public static void main(String[] args) {
Properties props = null;
ClientProperties p = new ClientProperties();
props = p.readPropertiesFromFile();
String xPanelsize = props.getProperty("xPanelsize");
System.out.println("Panel size x = " + xPanelsize);
p.setProperty("xPanelsize", "64"); // method not found error
p.writePropertiesToFile();
props = p.readPropertiesFromFile();
xPanelsize = props.getProperty("xPanelsize");
System.out.println("So, now the Panel size x = " + xPanelsize);
}
}
Here below am trying to read fileNames from a nested folder structure into a hashmap,
Structure is like
Main Folder
-> EN (SubFolder1)
-> File1
-> File2
-> FR (SubFolder2)
-> File3
-> File4
-> GE (SubFolder3)
-> File5
-> File6
HashMap contains "Sub FolderName" as Key & "FileNames"(ArrayList) as value.
I'm trying to make a recursive call & save things into HashMap, but missing something in that, things are not being saved into HashMap.
public static HashMap<String,ArrayList<String>> listFilesForFolder(File folder)
throws IOException {
HashMap<String, ArrayList<String>> dirFiles = new HashMap<String, ArrayList<String>>();
if(folder.isDirectory()) {
ArrayList<String> fileNames = new ArrayList<String>();
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
dirFiles.put(folder.getName(), fileNames);
} else {
String fileName = (fileEntry.getPath()).toString();
fileNames.add(fileEntry.getPath());
}
}
}
return dirFiles;
}
Please help me find out where am going wrong.
Input is the path of the parent directory.
Expected Output:
{"EN" = [File1, File2], "FR" = [File3, File4], "GE" = [File5, File6]}
Thank You.
Here is a solution using the JSR 203 API (which you should use for anything post 2011, provided you use Java 7+); the following code supposes Java 7+ (UNTESTED; but it should work):
public static Map<String, List<String>> listFiles(final Path baseDir)
throws IOException
{
final Map<String, List<String>> map = new HashMap<>();
try (
final DirectoryStream<Path> stream
= Files.newDirectoryStream(baseDir);
) {
for (final Path subdir: stream)
populateMap(map, subdir);
}
return ret;
}
private static void populateMap(final Map<String, List<String>> map,
final Path subdir)
throws IOException
{
// .getFileName() returns the last component of the path...
// REGARDLESS of whether that component is actually a "file"
final String dirname = subdir.getFileName().toString();
map.put(dirname, new ArrayList<>());
try (
final DirectoryStream<Path> stream
= Files.newDirectoryStream(subdir);
)
{
for (final Path entry: stream)
map.get(dirname).add(entry.getFileName().toString());
}
}
public class Folder {
public static HashMap<String, ArrayList<String>> dirFiles = new HashMap<String, ArrayList<String>>();
public static void listFilesForFolder(File folder)
throws IOException {
if(folder.isDirectory()) {
ArrayList<String> fileNames = new ArrayList<String>();
for (final File fileEntry : folder.listFiles()) {
// System.out.println(fileEntry.toString());
if (fileEntry.isDirectory()) {
// System.out.println(fileEntry.toString());
listFilesForFolder(fileEntry);
} else {
String fileName = (fileEntry.getPath()).toString();
fileNames.add(fileEntry.getPath());
}
}
dirFiles.put(folder.getName(), fileNames);
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
listFilesForFolder(new File("C:/Users/Guest/Documents/MainFolder"));
for(Entry<String, ArrayList<String>> foldername : dirFiles.entrySet())
{
System.out.println(foldername.getKey() + " " + foldername.getValue());
}
}
}
There are very minute changes need to be done in your code.
only when you loop through the entire list of files in
folder.listFiles(), fileNames arraylist get populated with the names
of files. Therefore I move the map put operation after the end of
loop.
you are creating Map object for every iteration, though you are
returning map object from the function which every recursive call
will do. you have to process all the map objects together. Hence a
global map object.
If you want to create a list of all directory and files under a directory use this:
private List<String> filesPath = new ArrayList<>();
public void createDirectoryMap() {
var storage = new File(path);
if (storage.isDirectory()) {
File[] children = storage.listFiles();
if (children != null) {
for (File childFile : children) {
getAllDirectory(childFile);
}
}
} else {
filesPath.add(storage.getPath());
}
// Save your list
filesPath.clear();
}
private void getAllDirectory(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File childFile : children) {
filesPath.add(childFile.getPath());
getAllDirectory(childFile);
}
}
}
}
And output will somethings like this:
storage\private\60af64d4146f1e6e70bef903
storage\private\60af64d4146f1e6e70bef903\DSC_0171.jpg
storage\private\60af64d4146f1e6e70bef903\icon.jpg
storage\public\blog
storage\public\blog\61afe3d311771928ca98f5f3
If you want your function to be recursive and keep the Map (although that's not the best choice), its definition should be :
Map<String,Map> listFilesForFolder(File folder);
I.e. the values of the map are map themselves or null meaning its a file.
This line has no effect if you don't use its result :
listFilesForFolder(fileEntry);
This is code to write hashtable to .txt file !
public static void save(String filename, Map<String, String> hashtable) throws IOException {
Properties prop = new Properties();
prop.putAll(hashtable);
FileOutputStream fos = new FileOutputStream(filename);
try {
prop.store(fos, prop);
} finally {
fos.close();
}
}
How we getback the hashtable from that file ?
Thanks
In the very same ugly manner:
#SuppressWarnings("unchecked")
public static Map<String, String> load(String filename) throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(filename);
try {
prop.load(fis);
} finally {
fis.close();
}
return (Map) prop;
}
Use Properties.load()
code example:
public static Properties load(String filename) {
FileReader reader = new FileReader(filename);
Properties props = new Properties(); // The variable name must be used as props all along or must be properties
try{
props.load(reader);
} finally {
reader.close();
}
return props;
}
Edit:
If you want a map back, use something like this. (The toString is to avoid a cast - you can cast to String if you would prefer)
public static Map<String, String> load(String filename) {
FileReader reader = new FileReader(filename);
Properties props = new Properties();
try {
props.load(reader);
} finally {
reader.close();
}
Map<String, String> myMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
myMap.put(key.toString(), props.get(key).toString());
}
return myMap;
}