I want to make a folder which contains files that my program made. For example (this example doesn't represent the things that my program actually does):
private static HashMap<LocalDate,Number> numbers = new HashMap<>();
private static ListIterator li;
public static void saveIndividually(){
try{
if(!numbers.isEmpty()){
ArrayList<LocalDate> lista= new ArrayList<LocalDate>(numbers.keySet());
li=lista.listIterator();
while (li.hasNext()){
Number number=numbers.get(li.next());
FileOutputStream ostreamPassword = new FileOutputStream(number.getDate()+".dat");
ObjectOutputStream oosPass = new ObjectOutputStream(ostreamPassword);
oosPass.writeObject(number);
ostreamPassword.close();
}
}
} catch (IOException ioe) {
System.out.println("Error de IO: " + ioe.getMessage());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
- My program makes random numbers combination.
- Every combination is stored in a HashMap
like so( I've added new code):
And now I want to make a .txt document individually for every number in the HashMap
, with the name datetime(when the number was created).txt
, and introduce all of them in a folder to make it easy for the user to read the combination without starting my program. Is it possible to do that in Java?
Let's answer "How to make a folder - in java". There are several ways to do this. Let's create an output folder on the Desktop for demonstration.
public static File createOutputFolder() {
final File desktop = new File(System.getProperty("user.home"), "Desktop")
final File output = new File(desktop, "output");
if (!output.exists()) {
// The directory does not exist already, we create it
output.mkdirs();
} else if (!output.isDirectory()) {
throw new IllegalStatexception("The output path already exists but is no directory: " + output);
}
return output;
}
Our method also returns the output directory. You may now pass this File
object to your FileOutputStream
and create new files like that:
File output = createOutputFolder();
FileOutputStream ostreamPassword = new FileOutputStream(new File(output, number.getKey()+".dat"));
Hopefully this answered your question. If not, please be more specific about the problem.